我在C中有以下代码:
#include <stdio.h>
void main() {
printf("%d %d\n",sizeof(5),sizeof(5,5));
printf("%d %d\n",sizeof(5),sizeof(5.0,5));
printf("%d %d\n",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)