Negation inside printf

好久不见. 提交于 2021-02-09 10:56:36

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!