我理解的结果
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.0
或 12
?
最佳答案
因为 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.0
和 nData += 2.0
的情况下,每个表达式的类型都是 int
,因为这是左边的类型-作业的手边。所以 sizeof
的计算结果为 int
的大小。
此外,sizeof
运算符的操作数仅在编译时 评估其类型。这意味着任何赋值或增量都不会在运行时求值。因此,在您的第二个示例中,nData
在使用 sizeof
的两行之后仍将具有值 10。 sizeof
的操作数在运行时被评估的唯一时间是操作数是否为可变长度数组。
关于c - sizeof 运算符的操作数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54462357/