C中的类型转换混淆
Type conversion confusion in C
#include <stdio.h>
int main()
{
char c = 255;
if (c > 128)
{
printf("This is unsigned number %d\n", c);
}
else
{
printf("This is signed number %d\n", c);
}
}
在这种情况下,当我们用 255 初始化范围从 -127 到 128 的有符号字符时会发生什么?它不会环绕,因为它是未定义的行为,但究竟发生了什么?
我的结果是 -1,但是如何以及为什么?
这不是明确定义的行为。标准6.3.1.3 §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.
这意味着结果取决于编译器。可能,您的编译器会尝试基于二进制补码进行某种环绕——这是最常见的行为。这不是未定义的行为。
请注意 char
类型可以是有符号或无符号的,这也取决于编译器。
#include <stdio.h>
int main()
{
char c = 255;
if (c > 128)
{
printf("This is unsigned number %d\n", c);
}
else
{
printf("This is signed number %d\n", c);
}
}
在这种情况下,当我们用 255 初始化范围从 -127 到 128 的有符号字符时会发生什么?它不会环绕,因为它是未定义的行为,但究竟发生了什么?
我的结果是 -1,但是如何以及为什么?
这不是明确定义的行为。标准6.3.1.3 §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.
这意味着结果取决于编译器。可能,您的编译器会尝试基于二进制补码进行某种环绕——这是最常见的行为。这不是未定义的行为。
请注意 char
类型可以是有符号或无符号的,这也取决于编译器。