Why variable n2 is 1 when it must be 0

59 Views Asked by At
#include <stdio.h>
int main()
{
    unsigned int n1 =2147483648,num=15;
    int n2=num & n1 >0;
    printf("%d",n2);
}

n2=1 but it should be 0 according to me.

1

There are 1 best solutions below

0
Vlad from Moscow On

Due to the operator precedence this record

int n2 = num & n1 >0;

is equivalent to

int n2 = num & ( n1 >0 );

that is the same as

int n2 = num & 1;

So the variable n2 is initialized by the value 1.

Tp get the expected result you need to write

int n2 = ( num & n1 ) > 0;

because n1 is internally is represented like (printf( "%#x\n", n1 ); )

0x80000000