c - 为什么这个 sizeof(c+a) 给出 4 个字节而不是 3 个字节

标签 c char int sizeof short

#include <stdio.h>
int main()
{
   short int a;
   char c;
   printf("%d %d %d",sizeof(a),sizeof(c),sizeof(c+a));
}

在这个 sizeof 中,a 是 2 个字节,char 的大小是 1 个字节,但我将它们加起来是 4 个字节。它在表达式内部做了什么使它成为 4

最佳答案

short int 添加到 char 会产生 int,这在您的系统上显然是 4 个字节。

这是“整数提升”的情况。参见 In a C expression where unsigned int and signed int are present, which type will be promoted to what type?寻求解释。规则相当困惑,但那里的答案解释得很好。

根据 the C standard6.3.1.8 普通算术转换 ,实际的转换规则是:

If both operands have the same type, then no further conversion is needed.

Otherwise, if both operands have signed integer types or both have unsigned integer types, the operand with the type of lesser integer conversion rank is converted to the type of the operand with greater rank.

Otherwise, if the operand that has unsigned integer type has rank greater or equal to the rank of the type of the other operand, then the operand with signed integer type is converted to the type of the operand with unsigned integer type.

Otherwise, if the type of the operand with signed integer type can represent all of the values of the type of the operand with unsigned integer type, then the operand with unsigned integer type is converted to the type of the operand with signed integer type.

Otherwise, both operands are converted to the unsigned
integer type corresponding to the type of the operand with signed integer type.

结果是 4,因为正如@WeatherVane 在评论中指出的那样:

5.1.2.3 para 11 示例 2 在执行片段中 char c1, c2;/* ... */c1 = c1 + c2; “整数提升”要求抽象机将每个变量的值提升为 int 大小,然后将两个 int 相加并截断总和。 但这里没有截断,因为目的地未知。

关于c - 为什么这个 sizeof(c+a) 给出 4 个字节而不是 3 个字节,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46715691/

相关文章:

java - 字符串不能改变。但是int、char是可以改变的

Python 类型转换

c - 使用 char 到 int 数据类型

java - 包含单个字符的字符串是否与 char 相同?

c++ - 指向数组指针的双星指针;如何访问数组的指针? C++

c - C语言中如何删除单链表?

c - __attribute__((packed)) 对嵌套结构数组的影响?

scala - 为什么 chisel UInt(32.W) 不能取 bit[32] 恰好为 1 的无符号数?

c - 带有 Redis 事件循环的 HTTP 服务器

c - 为什么c中的createfile函数停止for循环