为什么在C中,当多个操作数以逗号分隔传递时,函数sizeof()会输出最右边操作数的大小



我在C:中有以下代码

#include <stdio.h> 
void main() {
printf("%d %dn",sizeof(5),sizeof(5,5));   
printf("%d %dn",sizeof(5),sizeof(5.0,5)); 
printf("%d %dn",sizeof(5),sizeof(5,5.0)); 
}

我得到了输出:

4 4

4 4

4 8

我知道sizeof(5(会返回整数的大小,sizeof(5.0(会返回双精度的大小,但如果传递了多个以逗号分隔的参数,为什么它会给出最右边操作数的大小?为什么不是第一个论点或所有论点的集体规模?

我正在使用OnlineGDB.com编译器为C.进行在线编译

谢谢你的帮助。

原因很简单:因为sizeof不是函数它是一个在其右边取一些表达式的运算符。在语法上,它的行为与return运算符相同。括号只是程序员为了清楚起见才添加的,在大多数情况下不需要:

sizeof(foo);       //no surprise, take the size of the variable/object
sizeof foo;        //same as above, the parentheses are not needed
sizeof(void*);     //you cannot pass a type to a function, but you can pass it to the sizeof operator
sizeof void*;      //same as above
typedef char arrayType[20]
arrayType* bar;    //pointer to an array
sizeof(*bar);      //you cannot pass an array to a function, but you can pass it to the sizeof operator
sizeof*bar;        //same as above
//compare to the behavior of `return`:
return foo;     //no surprise
return(foo);    //same as above, any expression may be enclosed in parentheses

那么,当你说sizeof(5, 5.0)时会发生什么呢?好吧,由于sizeof是一个运算符,括号不是函数调用,而是像1*(2 + 3) == 5中的括号一样解释。在这两种情况下,(都遵循运算符,因此不被解释为函数调用。因此,逗号不会分隔函数调用参数(因为没有函数调用(,而是被解释为逗号运算符。逗号运算符被定义为计算其两个操作数,然后返回最后一个操作数的值sizeof的运算符性质决定了如何解析其右侧的表达式。

因为逗号运算符的关联性是从左到右的。

只使用最右边的表达,其余的都被丢弃(尽管它的副作用与测序有关(。

因此,

sizeof(5.0,5)相当于sizeof(5)

sizeof(5,5.0)相当于sizeof(5.0)

最新更新