c - sizeof 运算符的操作数

标签 c sizeof

我理解的结果

int nData = 10;
printf("%d", sizeof(nData + 2.0));

是“8”

为什么每个结果都是

int nData = 10;
printf("%d", sizeof(nData = 2.0));
printf("%d", sizeof(nData += 2.0));

不是8而是4?为什么 nData 不能通过 sizeof(nData += 2.0)12.012

最佳答案

因为 2.0 是 double 类型的常量,表达式 nData + 2.0 具有 double 类型,按照指定的“通常的算术转换”在 C 标准的第 6.3.1.8 节中:

First, if the corresponding real type of either operand is long double , the other operand is converted, without change of type domain, to a type whose corresponding real type is long double.

Otherwise, if the corresponding real type of either operand is double , the other operand is converted, without change of type domain, to a type whose corresponding real type is double

因此 sizeof 的计算结果为 double 的大小。

nData = 2.0nData += 2.0 的情况下,每个表达式的类型都是 int,因为这是左边的类型-作业的手边。所以 sizeof 的计算结果为 int 的大小。

此外,sizeof 运算符的操作数仅在编译时 评估其类型。这意味着任何赋值或增量都不会在运行时求值。因此,在您的第二个示例中,nData 在使用 sizeof 的两行之后仍将具有值 10。 sizeof 的操作数在运行时被评估的唯一时间是操作数是否为可变长度数组。

关于c - sizeof 运算符的操作数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54462357/

相关文章:

c++ - 推荐一个 C/C++ 中的 HTTP 解析库

c - 如何使用 xlib 获取现有窗口的显示结构

c - 为什么 "extern char name[]"中缺少数组索引不会影响 strlen(name) 但会导致 sizeof(name) 出错?

c - 将数据保存到二进制文件

c - 为什么 sizeof(function_name) 是 1

c - 为什么 str[5]、str[] = "1234"和 str = malloc(5) 有不同的大小?

c - 用 C/平均值/最大值中的随机数填充定义的二维数组

python - 在python中将类对象读/写到dat文件

c++ - 莱克斯/柔性 :Regular expression for string literals in C/C++?

c - 为什么数组参数的大小与 main 中的大小不同?