简体   繁体   English

在C中,为什么sizeof(char)1,当'a'是int时?

[英]In C, why is sizeof(char) 1, when 'a' is an int?

I tried 我试过了

printf("%d, %d\\n", sizeof(char), sizeof('c'));

and got 1, 4 as output. 得到1,4作为输出。 If size of a character is one, why does 'c' give me 4? 如果一个角色的大小是一个,为什么'c'给我4? I guess it's because it's an integer. 我想这是因为它是一个整数。 So when I do char ch = 'c'; 所以当我做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? 是否有一个隐式转换发生在引擎盖下,当它被分配给char变量时,从4字节值到1字节值?

In C 'a' is an integer constant (!?!), so 4 is correct for your architecture. 在C'中'是一个整数常量(!?!),因此4对于您的体系结构是正确的。 It is implicitly converted to char for the assignment. 它被隐式转换为char以进行赋值。 sizeof(char) is always 1 by definition. 根据定义,sizeof(char)始终为1。 The standard doesn't say what units 1 is, but it is often bytes. 标准没有说明单位1是什么,但它通常是字节。

Th C standard says that a character literal like 'a' is of type int, not type char. Th C标准说像'a'这样的字符文字是int类型,而不是char类型。 It therefore has (on your platform) sizeof == 4. See this question for a fuller discussion. 因此它(在您的平台上)sizeof == 4.请参阅此问题以进行更全面的讨论。

It is the normal behavior of the sizeof operator (See Wikipedia ): 这是sizeof运算符的正常行为(参见Wikipedia ):

  • For a datatype, sizeof returns the size of the datatype. 对于数据类型, sizeof返回数据类型的大小。 For char , you get 1. 对于char ,你得到1。
  • For an expression, sizeof returns the size of the type of the variable or expression. 对于表达式, sizeof返回变量或表达式的大小。 As a character literal is typed as int , you get 4. 由于字符文字输入为int ,因此得到4。

This is covered in ISO C11 6.4.4.4 Character constants though it's largely unchanged from earlier standards. 这在ISO C11 6.4.4.4 Character constants有所涉及,尽管它与早期标准基本没有变化。 That states, in paragraph /10 : 这表明,在第/10段中:

An integer character constant has type int. 整数字符常量的类型为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. 包含映射到单字节执行字符的单个字符的整数字符常量的值是解释为整数的映射字符的表示的数值。

According to the ANSI C standards, a char gets promoted to an int in the context where integers are used, you used a integer format specifier in the printf hence the different values. 根据ANSI C标准,在使用整数的上下文中将char提升为int ,在printf使用整数格式说明符,因此使用不同的值。 A char is usually 1 byte but that is implementation defined based on the runtime and compiler. char通常是1个字节,但这是基于运行时和编译器定义的实现。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM