char 类型是有符号还是无符号?
对于这个问题,有些功底不深的同学可能会回答“char 类型是有符号类型”,理由是省略 signed 是可以的。
而正确答案是:C99标准并未指定 char 类型是有符号还是无符号,这取决实现(编译器和硬件平台)。具体可以通过查看limits.h
头文件中 CHAR_MIN 的值来确认,如果 CHAR_MIN 为 0 则说明 char 类型被当作无符号整型。
关于这一点可以参考C99标准中的5.2.4.2.1小节,此处仅给出如下部分:
If the value of an object of type char is treated as a signed integer when used in an expression, the value of CHAR_MIN shall be the same as that of SCHAR_MIN and the value of CHAR_MAX shall be the same as that of SCHAR_MAX. Otherwise, the value of CHAR_MIN shall be 0 and the value of CHAR_MAX shall be the same as that of UCHAR_MAX. The value UCHAR_MAX shall equal 2CHAR_BIT − 1.
需要特别说明的一点是,无论 char 类型是被当作有符号还是无符号来处理,它与 signed char 和 unsigned char 都是不同的类型——即 char 、signed cahr 和 unsigned char 是三种不同的类型。可以参考C99标准 6.2.5 类型
这里我以常用的51单片机和STM32单片机在 keil 下编译为例,在 keil C51下编译51单片机的代码时,char 类型是当作有符号处理的。
而在 keil MDK 下编译stm32f407单片机的代码时,char 类型是当作无符号处理的。