0

Hello i have tried to understand the output of the following code in C but i dont get why x is x greater than y i.e why is x > y?

#include <stdio.h>

int main(){
   short a = -2;
   unsigned short b = -a;
   int x = -2;
   unsigned y = -x;

   if(a<(unsigned short)b)
       printf("a < b\t");
   else
       printf("a >= b\t");

   if((unsigned)x<y)
       printf("and x < y\n");
   else
      //my problem is here
       printf("and x >= y\n");
}
output : a < b and x >= y
0___________
  • 60,014
  • 4
  • 34
  • 74
H.Saad
  • 3
  • 3

1 Answers1

1

If you run this program:

#include <stdio.h> 
int main(void){
   short a = -2;
   unsigned short b = -a;
   int x = -2;
   unsigned y = -x;

   printf("a = %hd\n", a);
   printf("b = %hu\n", b);
   printf("x = %d\n", x);
   printf("y = %u\n", y);
   printf("(unsigned)x = %u\n", (unsigned)x);
   if(a<(unsigned short)b)
       printf("a < b\t");
   else
       printf("a >= b\t");
   if((unsigned)x<y)
       printf("and x < y\n");
   else
       printf("and x >= y\n");
}

the answer will be obvious. Why (unsigned)x is such a big number. It is because the x is a two's complement number. -2 in this format is 0xfffffffe

0___________
  • 60,014
  • 4
  • 34
  • 74