为什么sizeof(’a’)在C中是4?

可能重复:
为什么C字符文字而不是字符?

#include int main(void) { char b = 'c'; printf("here size is %zu\n",sizeof('a')); printf("here size is %zu",sizeof(b)); } 

这里输出是(在这里看现场演示。)

 here size is 4 here size is 1 

我不明白为什么sizeof('a')是4?

因为在C字符常量中,例如’a’具有int类型。

有一个关于这个项目的C FAQ :

也许令人惊讶的是, C中的字符常量是int类型 ,因此sizeof(’a’)是sizeof(int)(尽管这是C ++不同的另一个区域)。

以下是着名的C书 – 由Kernighan & Ritchie撰写The C programming Language关于单引号之间的字符的着名系列。

A character written between single quotes represents an integer value equal to the numerical value of the character in the machine's character set.

所以sizeof('a')相当于sizeof(int)

默认情况下,’a’是一个整数,因此你的机器中的int大小为4个字节。

char是1个字节,因此你得到1个字节。