c 程序的意外输出

Unexpected Output of c program

    void main()
    {
     clrscr();
     if(sizeof(!6.0))
     printf("%d",sizeof(6.0,2));
     else
     printf("i don't know");
     getch();
    }

The output of this function is 4. As I can understand in the expression if(sizeof(!6.0)) -> the expression sizeof(!6.0) returns: 0

so sizeof(0) is 4 (in 64 bit system) and expression if(sizeof(!6.0)) executes as its True. But in printf("%d",sizeof(6.0,2)) the output is 4 .

So I want to know why sizeof() is returning 4 byte and how can it take two values without any warning and error by compiler.

来自 C 标准(6.5.3.4 sizeof 和 alignof 运算符)

2 The sizeof operator yields the size (in bytes) of its operand, which may be an expression or the parenthesized name of a type. The size is determined from the type of the operand. The result is an integer. If the type of the operand is a variable length array type, the operand is evaluated; otherwise, the operand is not evaluated and the result is an integer constant.

与(6.5.3.3 一元算术运算符)

5 The result of the logical negation operator ! is 0 if the value of its operand compares unequal to 0, 1 if the value of its operand compares equal to 0. The result has type int. The expression !E is equivalent to (0==E).

因此在这个 if 语句中

if(sizeof(!6.0))

sizeof 运算符的操作数是一个带有否定运算符 ! 的表达式,类型为 int。所以实际上你有

if(sizeof(int))

sizeof( int ) 永远不会等于 0 因此 if 语句中的表达式求值为逻辑真,而 if 语句的子语句

printf("%d",sizeof(6.0,2));

取得控制权。

sizeof 运算符的操作数 sizeof(6.0,2) 是一个带逗号运算符的表达式。

来自 C 标准(6.5.17 逗号运算符)

2 The left operand of a comma operator is evaluated as a void expression; there is a sequence point between its evaluation and that of the right operand. Then the right operand is evaluated; the result has its type and value.

所以表达式的类型是int,也就是表示整型常量2.

的第二个操作数的类型

所以运算符再次等同于 sizeof( int ) 并且在您的系统中它等于 4.

编译器没有针对第一个操作数的计算无效的逗号运算符表达式发出警告,因为 sizeof 运算符不计算用作其操作数的表达式。它只决定表达式的类型。

注意您shell在此调用

中使用转换说明符%zu而不是%d
printf("%zu",sizeof(6.0,2));