C Programming Reference
 
C Programming Reference >> C  Programming Reference Question Bank >>

19/07/07 - 698 Views - Ratings :   3.78 of 5 / 9 Votes

Level - Intermediate
      

Question -

What will be the output of the following code and why?


main()
{
unsigned int y = 12;
int x = -2;
if(x>y)
printf (" x is greater");
else
printf (" y is greater");
return 0;
} Answer -
 x is greater
Explanation -

This code produces an outstandingly amazing result "x is greater" even though y is positive and x is negative and right from our birth we are taught a positive number is always greater than a negative number. So why such a result in programming, you may be wondering after all computers are definitely better in calculation then we are.

The reason for such a result is that both x and y are of slighlty diffrent type. X is signed integer while y is an unsigned integer. Now when the computer compares both of them x is promoted to an unsigned integer type.

When x is promoted to unsigned integer -2 becomes 65534 which is definately greater than 12. So result is produced x is greater than y.

Watch out for these minute details and dont let them throw you off track.

Reader Comments -

Author Comments
Add Comments 


Name :    
Reply :   


Rating :

Code :
Code

 

 
© 2006 cencyclopedia.com