C语言 在 C 中,当 'a' 是 int 时,为什么 sizeof(char) 为 1?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2252033/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
In C, why is sizeof(char) 1, when 'a' is an int?
提问by legends2k
I tried
我试过
printf("%d, %d\n", sizeof(char), sizeof('c'));
printf("%d, %d\n", sizeof(char), sizeof('c'));
and got 1, 4as output. If size of a character is one, why does 'c'give me 4? I guess it's because it's an integer. So when I do char ch = 'c';is there an implicit conversion happening, under the hood, from that 4 byte value to a 1 byte value when it's assigned to the char variable?
并得到1, 4作为输出。如果一个字符的大小是 1,为什么'c'给我 4?我想这是因为它是一个整数。因此,当我这样做char ch = 'c';时,当它分配给 char 变量时,是否会发生隐式转换,从 4 字节值到 1 字节值?
采纳答案by Richard Pennington
In C 'a' is an integer constant (!?!), so 4 is correct for your architecture. It is implicitly converted to char for the assignment. sizeof(char) is always 1 by definition. The standard doesn't say what units 1 is, but it is often bytes.
在 C 中,'a' 是一个整数常量 (!?!),所以 4 对您的架构是正确的。它被隐式转换为 char 以进行赋值。sizeof(char) 根据定义始终为 1。标准没有说明 1 是什么单位,但通常是字节。
回答by Richard Pennington
Th C standard says that a character literal like 'a' is of type int, not type char. It therefore has (on your platform) sizeof == 4. See this questionfor a fuller discussion.
C 标准说像 'a' 这样的字符文字是 int 类型,而不是 char 类型。因此,它(在您的平台上)sizeof == 4。有关更全面的讨论,请参阅此问题。
回答by Laurent Etiemble
It is the normal behavior of the sizeofoperator (See Wikipedia):
这是sizeof操作员的正常行为(参见维基百科):
- For a datatype,
sizeofreturns the size of the datatype. Forchar, you get 1. - For an expression,
sizeofreturns the size of the type of the variable or expression. As a character literal is typed asint, you get 4.
- 对于数据类型,
sizeof返回数据类型的大小。对于char,你得到 1。 - 对于表达式,
sizeof返回变量或表达式类型的大小。当字符文字输入为 时int,您会得到 4。
回答by paxdiablo
This is covered in ISO C11 6.4.4.4 Character constantsthough it's largely unchanged from earlier standards. That states, in paragraph /10:
这在 ISO C11 中有涵盖,6.4.4.4 Character constants尽管它与早期标准基本没有变化。在段落中指出/10:
An integer character constant has type int. The value of an integer character constant containing a single character that maps to a single-byte execution character is the numerical value of the representation of the mapped character interpreted as an integer.
整数字符常量的类型为 int。包含映射到单字节执行字符的单个字符的整数字符常量的值是解释为整数的映射字符表示的数值。
回答by t0mm13b
According to the ANSI C standards, a chargets promoted to an intin the context where integers are used, you used a integer format specifier in the printfhence the different values. A char is usually 1 byte but that is implementation defined based on the runtime and compiler.
根据 ANSI C 标准, a在使用整数的上下文中char被提升为 an int,printf因此您在不同的值中使用了整数格式说明符。一个字符通常是 1 个字节,但这是基于运行时和编译器定义的实现。

