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

时间:2017-02-21 16:18:58

标签: c casting sizeof

我在测试你的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));
}

为什么两种输出都不同?书中没有解释。

2 个答案:

答案 0 :(得分:9)

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

  

警告:声明无效[-Wunused-value]

第二个相当于sizeof(int),演员表是有效的。

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

那就是说,

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

答案 1 :(得分:1)

在第一个实例中,sizeof运算符返回double的大小。在第二个实例中,它返回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`.
相关问题