关于 C 中 sizeof 运算符的困惑

Confusion about sizeof operator in C

我对 C 中的 sizeof 运算符感到困惑。

#include <stdio.h>

int main(void)
{
    char num1=1, num2=2, result;
    result = num1 + num2;
    printf("Size of result: %d \n",sizeof result);
    printf("Size of result: %d \n",sizeof(num1+num2));
}

结果分别是1和4。为什么会这样?

resultchar 类型,因此 sizeof 给出 1num1+num2 提升为 int 类型因此它给出4int 的大小)。

注意,当对小于int的类型进行算术运算时,它的所有值都可以用int表示,那么结果将提升为int类型。

num1 + num2 正在变为整数,因此输出为 4,而结果为 char,输出为 1。

可以参考这篇文章Integer Promotion:

If an int can represent all values of the original type, the value is converted to an int; otherwise, it is converted to an unsigned int. These are called the integer promotions. All other types are unchanged by the integer promotions.

TL;DR 答案:

  • sizeof result 等同于 sizeof(char).
  • sizeof(num1+ num2)sizeof (int) 相同 为什么?

在您的情况下,它们分别产生 1(标准保证)和 4(可能不同)。

也就是说sizeof产生了size_t类型的结果,所以你应该%zu格式说明符来打印值。


为什么:

首先,对于加法运算符+,引用C11,章节§6.5.6

If both operands have arithmetic type, the usual arithmetic conversions are performed on them.

关于常规算术转换,§6.3.1.8/p1

[....] Otherwise, the integer promotions are performed on both operands.[...]

然后从 §6.3.1.1,/p2,

If an int can represent all values of the original type (as restricted by the width, for a bit-field), the value is converted to an int; otherwise, it is converted to an unsigned int. These are called the integer promotions.

因此,sizeof(num1+num2)sizeof(int) 相同。

一个字符的大小是 1 个字节,一个字符最多可以容纳 127 个值(无符号数最多 255 个)。 当您说类似 (a + b) 的内容时,将创建一个临时变量并将其用于将 a 添加到 b,因为 a 和 b 只能容纳 127,因此编译器会将它们提升为 int,以确保万无一失。

这是合乎逻辑的,因为如果 a = 100 和 b = 100,用户希望在添加它们时看到 200 而不是 73(这是溢出的结果)。