Rajesh Rajesh - 2 months ago 9
C Question

Negation inside printf

I have the below code and I am not sure why negation inside printf is different from doing negation outside?

char d=0x04;
printf("Value of d= %X\n",~d);
printf("Value of d= %X\n",d);

The result printed is FFFFFFFB and FB.
That means can I say that, inside printf, expressions are converted to integer type (default promotion) and hence 4 bytes are appearing!


Before the operation of the ~ operator is performed, the type of the operand it promoted to int. This means the result of: ~0x04 will be 0xFFFFFFFB in your case, as the width of type int appears to be 32 bits.

If the value 0xFFFFFFFB is passed to printf it isn't promoted to int as it is already of that type, and it is printed out.

If 0xFFFFFFFB is assigned back to d, a conversion from int to char in an implementation-defined manner is done. In your case the resulting value is: 0xFB. When d is passed to printf, it gets promoted to int, the value of 0xFB when promoted to int stays the same, and it gets printed out.