Yahoo Answers is shutting down on May 4th, 2021 (Eastern Time) and beginning April 20th, 2021 (Eastern Time) the Yahoo Answers website will be in read-only mode. There will be no changes to other Yahoo properties or services, or your Yahoo account. You can find more information about the Yahoo Answers shutdown and how to download your data on this help page.
Trending News
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!
3 Answers
- AnalProgrammerLv 78 years agoFavorite 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.
- DavidLv 68 years ago
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).
- Anonymous8 years ago
The other answers are correct. -1 is an easy way to intitialize an int to all binary 1's (0xffffffffffffffff....)