输出结果是 128 的 32 位 2 的补码,即 4294967168。如何?
#include <stdio.h>
int main()
{
char a;
a=128;
if(a==-128)
{
printf("%u\n",a);
}
return 0;
}
最佳答案
在打开警告的情况下编译代码会给出:
warning: overflow in conversion from 'int' to 'char' changes value from '128' to '-128' [-Woverflow]
这告诉您作业 a=128;
在您的平台上没有明确定义。
标准说:
6.3.1.3 Signed and unsigned integers
1 When a value with integer type is converted to another integer type other than _Bool, if the value can be represented by the new type, it is unchanged.
2 Otherwise, if the new type is unsigned, the value is converted by repeatedly adding or subtracting one more than the maximum value that can be represented in the new type until the value is in the range of the new type.
3 Otherwise, the new type is signed and the value cannot be represented in it; either the result is implementation-defined or an implementation-defined signal is raised.
所以我们不知道发生了什么,因为这取决于您的系统。
但是,如果我们进行一些猜测(注意这只是一个猜测):
128 作为 8 位将是 0b1000.0000
因此,当您调用 printf
时,您会得到一个转换为 int
的符号扩展名,例如:
0b1000.0000 ==> 0b1111.1111.1111.1111.1111.1111.1000.0000
其中 - 打印为无符号表示数字 4294967168
关于c - 将128分配给c中的char变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51047929/