在C++中將-1指定給unsigned char

  • 554
  • 0
  • 2017-08-31

在C++中將-1指定給unsigned char

在C++中,將-1指定給unsigned char宣告的變數c,再將變數c指定給int宣告的變數i,最後將變數i輸出至螢幕的結果是255。

#include<iostream>


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