gpt4 book ai didi

c - sizeof 运算符的操作数

转载 作者:太空狗 更新时间:2023-10-29 15:17:21 26 4
gpt4 key购买 nike

我理解的结果

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com