为什么这两种情况有不同的行为?第一种情况是 int i = 1,2,3;,第二种情况是 int i; i = 1,2,3;。

5
在GCC编译器上工作时,针对C程序中以下两种运算符的情况观察到了不同的行为。
1.
 int i = 1,2,3;

 printf("%d",i);                     // this will give compile time error

并且,
2.
int i;

i = 1,2,3;

printf("%d",i);    // Its output will be 1.

在第一个案例中,编译器给出了错误提示“error: expected identifier or ‘(’ before numeric constant”。在第二个案例中,没有错误,并且输出结果为1。有人可以在这里详细解释一下编译器两种情况下的行为吗?编译器如何解释这两个语句?
非常感谢您提供的意见。

@haccks 对我输出1。 - amdixon
@amdixon; 我想错了。它将会并且应该输出 1 - haccks
1个回答

9
  1. In the first case the comma separates declaration and initialisation of several variables of the same type:

    int i = 1, j = 2, k = 3;
    

    You can add parentheses to tell the compiler it's an expression.

    int i = (1, 2, 3);
    

    If you combine them, it's easier to see why the comma is ambiguous without parentheses:

    int i = (1, 2, 3), j = 4, k = 5;
    
  2. In the second case the comma separates 3 expressions.

    (i = 1), 2, 3
    

我其实有点惊讶第一种方式没有“起作用”。 - John Zwinck
2
@JohnZwinck 这只是语法的一个细节,C++实际上没有具有优先级的运算符,而是有不同类型的表达式,具有逗号运算符的表达式类型在该上下文中不允许。加上一些括号就可以了,int i = (1, 2, 3); 是可以工作的。 - john
@JohnZwinck 我已经添加了一个示例,说明为什么它不起作用。 - Alex B
2
准确地说:i = 1, 2, 3没有任何歧义,因为逗号的优先级低于赋值运算符。因此,子表达式是i = 123。整个表达式的副作用是将1分配给i和3的值。 - cmaster - reinstate monica
在第二种情况下,输出不应该是“3”吗? - haccks
显示剩余2条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接