Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c puzzle(if statement) [closed]

Tags:

c

what is data(number), if the required output from the following statement is is : AMAZING?

main()
{
 int data;
 if(data!=0 && data==-data)
 {
  printf("AMAZING");
 }
}
like image 339
Sharat Malaler Avatar asked Feb 05 '10 12:02

Sharat Malaler


1 Answers

It'd have to be the minimum value of an integer, i.e. 0x80000000 if it's 32-bits, because that's the only number other than zero that remains the same 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 the two's complement representation of 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 an int and wraps around, giving back the same number.

For computers that use one's complement, every representable number's negative value can also be represented without overflow so this puzzle doesn't have a solution.

like image 179
Mark Byers Avatar answered Oct 10 '22 19:10

Mark Byers