问题
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);
d=~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!
回答1:
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.
来源:https://stackoverflow.com/questions/38741805/negation-inside-printf