[OCLUG-devel] ArrayMaxValue() - how could I improve it?
James Colannino
james at colannino.org
Thu Jun 3 00:05:07 PDT 2004
Tim Thelin wrote:
> James Colannino wrote:
>
>> I know that one limitation I'd like to do away with is the fact that
>> instead of just parsing through the array until the user's input is
>> finished, it's going to go all the way up to element 20, even if the
>> user only enters two or three numbers.
>
>
> There are two ways to deal with this, either have a value in the array
> which means "i'm an endpoint so don't go past me" or you store the
> number of valid entries somewhere.
>[...]
> An example of the second case would be having a data structure that
> contained your array and had a size field.... so something like
> struct mydata
> {
> int array[ 20 ];
> int numValidEntries;
> }
That looks interesting. I haven't covered structures yet so I'm not
quite sure how that works, but I'm sure I'll understand it better once I
get to that chapter :)
> Also, make use of the C++ "//" style comments as (at least for me) its
> less visual clutter than "/* ... */" everywhere.
I know that all modern compilers will accept the C++ style comments in C
code, but would an older compiler accept it as well? I doubt that
anything I'd ever be doing would involve an old compiler, but still, I'd
like to know that my code is portable. I actually do prefer '//' to
'/*... */'.
> Btw a "for" loop would probably be better than the "while" (did the book
> cover "for" loops yet?)
Yup, I've been introduced to for loops. I actually just didn't think
about the fact that I could implement it here :-P Probably would be best...
> Btw, potential issues in the code that can cause bugs:
> * I don't see "position" incremented anywhere in your function... so is
> it really looping through the array correctly?
Yup, you're right. I forgot to place my position++; statement in there.
I haven't debugged the function yet, so that'll save me some
embarrasing frustration later ;)
> * MaxValue starts at 0, so if your array was all negative numbers ( i.e.
> { -1, -100, -60 } ), it would return 0 instead of the largest negative
> (i.e. -1)
True. Perhaps I could initialize the variable by instead assigning the
first value of the array to MaxValue (MaxValue = array[0];) and then let
it go on from there to find the largest number.
James
--
My blog: http://www.crazydrclaw.com/
My homepage: http://james.colannino.org/
"There are no uninteresting things; only uninterested people." --G.K.
Chesterton
More information about the OCLUG-devel
mailing list