Hello experts, please consider the code fragment:-
#include<stdio.h>
#define TOTAL_ELEMENTS (sizeof(array)/sizeof(array[0]))
int array[] = {23,34,12,17,204,99,16};
int main()
{
int d;
for(d=-1;d <= (TOTAL_ELEMENTS-2);d++)
printf("%d\n",array[d+1]);
return 0;
}
It doesn't print the elements of the array?
Fiddle with it. Change little things to see if you can get the problem
to go away. Ponder how this loop is different from normal loops, and
what influence this could have on the result.
If you're still stuck, here are a couple of successive hints:
Hint 0: What actually happens in the comparison in your for statement?
Hint 1: sizeof gives a size_t. What is a size_t?
Hint 2: size_t is an unsigned type.
Hint 3: What happens when you have a (possibly large) unsigned type and
a signed int in a comparison?
Hint 4: For the comparison d <= (TOTAL_ELEMENTS-2), d is converted to
an unsigned type compatible with size_t, not v.v. What is the result?
Hint 5: d starts out negative. What happens when you convert a small
negative int to a large unsigned type?
Hint 6: What could you to to ensure that the comparison is done using
(signed) ints?
No more hints. The next explanation is explicit.
For the comparison in the for loop, d is converted to a size_t, and then
both unsigned values are compared. This would not usually be a problem,
_except_ that d starts out as -1, which is converted to SIZE_MAX-2 - a
very _large_ positive number, not a negative one. So on the first tour
through the for loop, the comparison fails.
To get around this, you could, for example, cast TOTAL_ELEMENTS or
(TOTAL_ELEMENTS-1) to int. This makes the comparison one between two
signed integers; no more conversion is needed; and the comparison works
as you'd expect it to.
Richard