in Programming in C
1,413 views
1 vote
1 vote
#include <stdio.h>
main (){
unsigned x = -10;
int X = 20;
if (X > x)
      printf  ("Hello");
else{
      printf ("%d",x);
      printf ("Jello");
      }
}
in Programming in C
by
1.4k views

1 comment

I got the output will be Jello,  but when I print x it's printing -10 , why not INT_MAX-10 ??

Or do I have to write %ud and print it ?
0
0

1 Answer

2 votes
2 votes
Best answer

Yeah very good question and thanks for asking ...

In the above example, I am assuming the size of the integer is a 4 bytes (32 bit). Let us assume that the compiler represents signed negative integers number in 2’s complement notation. when casting the negative integer number than no bits will be changed the only compiler treat the stored bits as the unsigned integer.  

Question

Now -10 will be stored as 2's complement form and after unsigned the  value of the variable stored in 2's complement does not changed only type is changed.

if i take only 8 bit to represent -10 then 

2's complement of -10:= 11110110

Now after unsigned it is (11110110) in decimal 246.

x=246 

X=20

if(X>x) is now false then else block will be executed .

Because u have use

 printf("%d" ,x) which is used to get integer values . so if u replace it with %ud then u will get the point .

#include <stdio.h>
int main(void)
{
int i = -6;
unsigned int ui = (unsigned int)i;
printf("%d %ud\n",ui,ui);
return 0;
}

 

selected by

2 Comments

Brother when I print %ud I get a very big number not 246 ? I guess it's INT_MAX - 10 I am getting
0
0
Yeah Bro you are right it will be INT_MAX-10 , Actually i have supposed only for 8 bits. But your compiler(code block) is using 32 bits. If you consider 32 bits then you will get 4294967286 because INT_MAX=4294967296 so INT_MAX-10 =4294967286.

As if you use 8 bits as = 11111111

then if you use %d=-127 As first bit is taken as signed bit

 %u or %ud=255.
1
1

Related questions