A
August Karlstrom
Eric said:August said:Joe said:Using break; is ugly. Consider..
int lookup(int val, const int array[], int len)
{
int i, ret = -1;
if (array != NULL && len > 0) {
for (i = 0; i < len; ++i) {
if (val == array) {
ret = i; /* set the return value */
i = len; /* kill the for loop */
}
}
}
return ret;
}
I think a while-loop is even clearer:
int lookup(int val, const int array[], int len)
{
int i, ret = -1;
if (array != NULL && len > 0) {
i = 0;
while ((i < len) && (val != array)) {
i++;
}
if (val == array) {
ret = i;
}
}
return ret;
}
It might be clearer, but it's also wrong. On any
unsuccessful search, the loop terminates with i==len.
Then the test val==array gives undefined behavior due
to the out-of-bounds array index.
Yes, of course. How careless of me. It should be:
int lookup(int val, const int array[], int len)
{
int i, ret = -1;
if (array != NULL && len > 0) {
i = 0;
while ((i < len) && (val != array)) {
i++;
}
if (i < len) {
ret = i;
}
}
return ret;
}
August