#include<stdio.h>
int main()
{
unsigned char c;
c = 300;
printf("%d",c);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
输出是否可以预测或未定义?
Ara*_*raK 10
对不起第一个答案,这里是C++标准的解释:)
输出是否可以预测或未定义?
这是可以预测的.在此代码中有两点需要注意:首先,类型unsigned char无法保存的值的赋值:
unsigned char c;
c = 300;
Run Code Online (Sandbox Code Playgroud)
3.9.1基本类型(页54)
无符号整数,声明为无符号整数,应遵守算术模2n的定律,其中n是整数特定大小的值表示中的位数 .41)
...
41)这意味着无符号算术不会溢出,因为结果无法用结果无符号整数类型表示的数字减去模数,该数字大于可由结果无符号整数类型表示的最大值.
基本上:
c = 300 % (std::numeric_limits<unsigned char>::max() + 1);
Run Code Online (Sandbox Code Playgroud)
其次,传入打印变量%d的格式字符串.
这个是正确的;)没有未定义的行为,因为在无情签名的情况下,从unsigned char到int的促销转换!printfunsigned charvariadic arguments
注意:答案的第二部分是一个重新措辞什么都在一直说的这个答案的评论,但它不是我的回答原来.