Powered By Blogger

Thursday 28 April 2011

A tricky C program where a negetive no is shown as greater than positive one. But its not by mistake, there is a definite computing logic.

#include<stdio.h>
#include<conio.h>
int main(void)
{
  unsigned int y = 12;
  int x = -2;
 
   if(x>y)
     printf   (" x is greater");
  else
     printf (" y is greater");
   getch();
 
return 0;
}



OPTPUT:
x is greater





LOGIC:

The reason for such a result is that both x and y are of slightly different 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 definitely greater than 12. So result is produced x is greater than y.

4 comments:

  1. Man....u r awesome....i didnt knew that....keep posting such interesting programmes !!

    ReplyDelete
  2. Thnx buddy... I will try my best :)

    ReplyDelete
  3. Thank you for sharing Amazing Blog. It's providing very useful guideline for Engineering students.
    get more: Programming Language in C


    ReplyDelete