sizeof('0') 的值是多少?

the value of sizeof('0') is how much?

#include <stdio.h>
int main()
{
    char c = '0';
    printf("%d %d",sizeof(c), sizeof('0'));
    return 0;
}

我希望输出是 1 1.but 实际结果是 1 4.

与 C++ 中的 C(整数)字符常量相反,其类型为 int

来自 C 标准(6.4.4.4 字符常量)

10 An integer character constant has type int.

将引用与 C++17 标准(5.13.3 字符文字)中的引用进行比较

2 A character literal that does not begin with u8, u, U, or L is an ordinary character literal. An ordinary character literal that contains a single c-char representable in the execution character set has type char, with value equal to the numerical value of the encoding of the c-char in the execution character set....

至于这个表达

sizeof(c)

然后它提供 char 类型对象的大小。 char 类型的对象的大小始终等于 1.

来自 C 标准(6.5.3.4 sizeof 和 alignof 运算符)

4 When sizeof is applied to an operand that has type char, unsigned char, or signed char, (or a qualified version thereof) the result is 1....

注意函数 printf 的有效调用看起来像

printf("%zu %zu",sizeof(c), sizeof('0'));
sizeof('0')

实际上是

sizeof(ASCII value of '0')

这是整数。因此它正在打印 sizeof(int).

C 中的字符文字('0''a''d''.')是 int 类型(与 C++ 不同,它们是类型 char).

所以你会进入C:

sizeof(char) == 1
sizeof('0')  == sizeof(int) // note that this is not necessarily 4!

而在 C++ 中,您将拥有:

sizeof(char) == 1
sizeof('0')  == sizeof(char)