tags:

views:

190

answers:

2

In the following code segment what will be the result of the function, value of x , value of y

{

   unsigned int x=-1;
   int y;
   y = ~0;
   if(x == y)
     printf("same");
   else
     printf("not same");

}

Please explain how this works. From my side its answer will be "not same" but its actual answer is "same".

+2  A: 

To understand what is going on, you need to understand how the value of (-1) is stored in memory.

Daryl Hanson
+1  A: 

I will give you hints so that you can figure out the explanation for yourself.

  1. Note, x is unsigned int where as y is signed int.

  2. Did you learn about bit-wise operators?

  3. Alter your program by including the following at the end and see for yourself:

    printf("x = %d, y = %d", x, y);

EDIT: Changed the printf statement to:

printf("x = %d, x = %u, y = %d, y = %u, ", x, x, y, y);
anand.arumug