What is the answer to this C program?

int array[]={1,2,3,4,5,6,7,8};
#define SIZE (sizeof(array)/sizeof(int))
main() {
if(-1<=SIZE) printf("1");
else printf("2");
}

Here, I can see that the value of SIZE would be 8 and the if condition is if(-1<=SIZE), which is true. So theoretically the output should be 1 but when i execute the program on my pc, it says the answer is 2. How and why?? Please explain clearly.. Thank you!

AnalProgrammer2013-02-16T06:34:40Z

Favorite Answer

There are two things going on here.
First SIZE does not equal 8. It may result in 8 though.
SIZE is a pre-processor directive. So everywhere in the source that you write SIZE the pre-processor places -
(sizeof(array)/sizeof(int))

Now -1. Computers use 2's complement to represent negative numbers. -1 is therefore going to be all bits on.
So if sizeof gives an unsigned result when compared to all bits on then it is never going to be less than.

Have fun.

David2013-02-16T14:22:06Z

SIZE is unsigned (sizeof returns size_t) so there is an implicit conversion of -1 to unsigned in which case there is an overflow so it wraps around to the largest unsigned integer (which on my system is 42949672952).

Anonymous2013-02-16T15:44:56Z

The other answers are correct. -1 is an easy way to intitialize an int to all binary 1's (0xffffffffffffffff....)