#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 does not print anything. the reson i think its not printing
anything because of the comparison returning false. Why is the
condition not true?
please help me with this problem.
sizeof returns size_t which is unsigned. So (TOTAL_ELEMENTS-2) is
unsigned.
C converts d to unsigned before comparing.
-1 becomes a large number and condition became false.
Here's a simplified example:
This program prints nothing:
#include<stdio.h>
int main(void)
{
int d;
size_t max = 5;
for(d = -1; d <= max; d ++) {
printf("d = %d\n", d);
}
return 0;
}
This one works:
#include<stdio.h>
int main(void)
{
int d;
int max = 5;
for(d = -1; d <= max; d ++) {
printf("d = %d\n", d);
}
return 0;
}
The problem is that TOTAL_ELEMENTS expands to an expression of type
size_t. When you apply an operator ("<=" in this case) to an int and
a size_t (an unsigned type), the int value is promoted to size_t.
Converting the value -1 to size_t yields a large positive value,
typically 2147483647 if size_t is 32 bits.
Casting TOTAL_ELEMENTS to int is one workaround (one of the few cases
where a cast isn't a bad idea).
--
Keith Thompson (The_Other_Keith) ks...@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
This huge number will be compared to 5, and the condition does not hold,
so nothing is printed and the program exits.
FIX:
> for(d=-1;d <= (int)(TOTAL_ELEMENTS-2);d++)
Note the (int) cast.
jacob
> #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 does not print anything. the reson i think its not printing
> anything because of the comparison returning false. Why is the
> condition not true?
Hint: d is signed, TOTAL_ELEMENTS-2 is unsigned.
#include <stdio.h>
int main(void)
{
printf("%u\n", (unsigned)(-1));
return 0;
}