在C++中将

在C++中将-1指定给unsigned char


在C++中,将-1指定给unsigned char声明的变量c,再将变量c指定给int声明的变量i,最后将变量i输出至屏幕的结果是255。

#include


void test0()
{
	unsigned char c = -1;
	int i = c;
	std::cout << "Print I " << i << std::endl;
	std::cin >> c;
}

void test1()
{
	int i = -1;
	int j = i % 256;
	std::cout << j << std::endl;
	std::cin >> i;
}

void test2()
{
	//unsigned char c = 256;
	unsigned char c = 65537;
	int i = c;
	std::cout << "Print I " << i << std::endl;
	std::cin >> c;
}

int main()
{
	test0();
	//test1();
	//test2();
	return 0;
}
原因:-1不能被unsigned integer type呈现,而且-1小于256(unsigned char的长度是2的8次方,可以容许的范围是0~255),所以隐含unsigned arithmetic并不是overflow。
输入的数据与输出的结果如下表:
输入 输出
-1 255
-2 254
-256 0
-257 255
-258 254
-259 253

由上表的数据推论,应该是将输入值与256相加,得到输出值,若输出值小于0,则以255呈现。 应该是将被除数除以除数(256)之后的余数再与除数(256)相加。

以下是将C++ Language Standard的节录内容重新断句以利阅读与理解。
This implies that unsigned arithmetic does not overflow
 because a result
  that cannot be represented
   by the resulting unsigned integer type
  is reduced
  modulo the number
   that is one greater than the largest value
    that can be represented by the resulting unsigned integer type.
C++ 11 Language Standard § 3.9.1/4

[1]What will happen if I assign negative value to an unsigned char?
https://stackoverflow.com/questions/41276869/what-will-happen-if-i-assign-negative-value-to-an-unsigned-char
[2]C++ Primer 5/e, p35
[3]Standard for Programming Language C++
http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n4296.pdf