2011-12-28 85 views
9

可能重复:
Why are C character literals ints instead of chars?为什么sizeof('a')在C中是4?

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

这里输出(见现场演示here

here size is 4 
here size is 1 

我没有得到为什么sizeof('a')是4?

+0

参见[为什么是C字符文字整数,而不是字符?(http://stackoverflow.com/questions/433895/why-are-c-字符文字,整数,INSTEAD-OF-字符) – 2011-12-28 10:46:44

回答

10

因为在C字符常量中,比如'a'的类型为int

有一个C FAQ这个主体探析:

也许令人惊讶,在C 字符常量是int类型,所以 的sizeof( 'A')中的sizeof(int)的(虽然这是另一个领域其中C++ 不同)。

3

默认情况下'a'是一个整数,因此你在你的机器上得到int的大小4个字节。

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

10

以下是着名的C这本书 - The C programming LanguageKernighan & Ritchie相对于单引号之间写的字符。

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)

相关问题