今天看C++ Primer读到关于char的介绍时发现和我之前认识的不一样。书上原文这样:

"Unlike the other integer types, there are three distinct basic character types: char, signed char and unsigned char. Inparticular, char is not the same type as signed char. Although there are three character types, there are only two representations: signed and unsigned. The(plain) char type uses one of these two representations. Which of the other two character representations is equivalent to char depends on the compiler".

大体意思就是,在C/C++中char有三种类型。其中(plain)char是不确定的,他可能代表signed char,也可能是unsigned char,具体是那种取决于编译器。

之前学C的时候也没注意到这个问题,一直认为char 就是signed char.在网上找了很多资料总算是理解了.

char ,signed char, unsigned char 占据的空间都是一样的,对于存储的同样一段八位二进制序列,具体的值是多少取决于怎么读他.计算机存储的时候是按照补码存储的,而正负数的补码是不同的.所以很有必要区分开char到底代表什么(不过最好的作法应该是使用signed char 和unsigned char),通过一个简单的程序可以测试.

#include<iostream>
int main()
{
	char t=0xff;
	std::cout<<(int)t<<std::endl;
	return 0;
}

 若输出为 -1,则char和signed char是一样的;若输出255,则char和unsigned char是一样的。