C puzzle (if statement)

What is data (number) if the required conclusion from the following statement: AMAZING?

main() { int data; if(data!=0 && data==-data) { printf("AMAZING"); } } 
+6
c
source share
3 answers

This should be the minimum value of the integer, i.e. 0x80000000, if it is 32-bit, because it is the only non-zero number that remains unchanged when negated.

 #include <stdio.h> main() { int data = 0x80000000; if(data!=0 && data==-data) { printf("AMAZING"); } } 

Result:

 AMAZING 

As Richard Pennington correctly pointed out, this works because of two additions to represent negative numbers. The largest representable positive number is one smaller in absolute value than the largest negative number, so if you try to negate the largest negative number, it overflows int and wraps, returning the same number.

For computers that use one additional option , each represented negative value of a number can also be represented without overflow so that this puzzle has no solution.

+12
source share

It depends on the size of the integer and how the integers are implemented, but on a two-component machine with 2 byte targets, the answer is -32768.

+7
source share

I do not know what size int is in my machine. so I used the program to find the maximum int value as

 void main() { int i; do{ }while(i>i++); printf ("data=%d",i); } 

I found the maximum value i = -2147483648

assign it to data, it will work.

0
source share

All Articles