为什么 C 中的 sizeof() 运算符输出不同

Why the sizeof() operator different output in C

我在 test your c(作者:Yashvant Kanetkar) 中看到了以下示例。

在以下示例中,sizeof() 给出输出 8

#include<stdio.h>

double d;

int main()
{
(int)(float)(char)d;
printf("%d\n",sizeof(d));
}

但在第二个示例中,sizeof() 给出输出 4

#include<stdio.h>

double d;

int main()
{
printf("%d\n",sizeof((int)(float)(char)d));
}

为什么两者输出不同?书上没有解释。

第一种情况相当于sizeof(double)。演员,在那里没用。 d 的有效类型保持不变。在启用适当警告的情况下编译您的代码,您会看到一些警告,例如

warning: statement with no effect [-Wunused-value]

第二个相当于sizeof(int),转换有效

您看到的结果(intdouble 的大小)基于您的平台/环境。

也就是说,

  • sizeof 产生 size_t 类型的结果,您必须使用 %zu 格式说明符来打印结果。
  • 托管环境中 main() 的一致性签名至少是 int main(void)

在第一个实例中,sizeof 运算符 returns 的大小为 double。在第二个实例中,它 returns 的大小为 int

原因

首先,

(int)(float)(char)d; //This doesn't do anything effective.
printf("%d\n",sizeof(d)); //d is still `double`.

在第二个实例中,

//You are type casting d to float and then to int and then passing it to the operator sizeof which now returns the size of int. 
printf("%d\n",sizeof((int)(float)(float)d)); //d is `int` now when passed to `sizeof`.