Re: Max/Min Functions

Tech-Archive recommends: Speed Up your PC by fixing your registry



On Sat, 3 Dec 2005 21:28:14 -0500, "Greg Maxey"
<gmaxey@xxxxxxxxxxxxxxxxxxx> wrote:

>Jay,
>
>You said the Array function won't work here. I agree that with the a value
>in the () in the Dim statement it won't. However, if leave that blank I can
>use the Array function like:
>
>Sub CallMacro()
>Dim myArray() As Variant
>myArray = Array(3, 1.5, -13.32, 5000.34)
>MsgBox MaxOfArray(myArray)
>MsgBox MinOfArray(myArray)
>End Sub
>
>Is there hidden dangers here?

Yes, that works. And it has no more or less dangerous possibilities
than the code I showed you before.

The danger that Jezebel warned about is in both versions: a Variant
can contain *anything*. For example, replace your Array statement with

myArray = Array(3, "fred", -13.32, 5000.34)

and watch what happens. It runs, it doesn't throw any errors, and it
tells you that the maximum value is "fred". :-) Now, I'm not sure
exactly how the greater-than operator decides whether a non-numeric
string is or isn't greater than a number, but clearly this isn't the
behavior you really want.

You'd see the same behavior if you took my code and changed one of the
assignments to something like

myArray(1) = "fred"

The solution is not necessarily to change the assignments in the main
routine, but to check each value in the Min and Max subroutines to
verify that it's numeric before using it:

If (IsNumeric(vArray(i))) And _
(vArray(i) > vMax) Then vMax = vArray(i)

This is a general rule for helping to create crash-proof software:
Never assume anything about the input data; always check everything.
For example, you may have heard about "buffer overruns" and how they
can be exploited by hackers. The cause of this problem is that a lot
of software simply assumed that the input will fit into the buffer
(memory area) that was allocated for it, but hackers figured out that
they could cause "unanticipated behavior" by feeding in strings that
are too long to fit. The fix is to check the size of every input
before accepting it. This business of Variant values is similar: when
your data can be of any type, you need to verify that it actually has
the type you want.

--
Regards,
Jay Freedman
Microsoft Word MVP FAQ: http://word.mvps.org
Email cannot be acknowledged; please post all follow-ups to the
newsgroup so all may benefit.
.