逗号运算符和分号之间有什么实际的语义区别吗?

Is there any practical semantic difference between the comma operator and the semicolon?

这是我目前的理解:

  1. 逗号运算符允许代码简洁,例如int x = 0, y = 0, z = 0 而不是 int x = 0; int y = 0; int z = 0;。在这种情况下,它有点像分号的语法糖。

  2. 逗号运算符充当序列点。所以在代码 f(), g(); 中,函数 f() 保证在 g() 之前执行并产生它的所有副作用。但是如果使用代码f(); g();.

  3. 也是一样的
  4. 逗号运算符是一个运算符,而分号只是一个不参与表达式计算的程序标记。由于逗号运算符的优先级如此之低,因此在这方面它与分号的区别很小。

所以,我想知道这两种结构在实践中的语义区别是什么?在任何情况下,使用逗号会产生与使用分号不同的结果吗?

有些情况下逗号用作标记,有些情况下逗号是 comma operator.

引用维基百科,

The use of the comma token as an operator is distinct from its use in function calls and definitions, variable declarations, enum declarations, and similar constructs, where it acts as a separator.

一个例子来澄清,(直接从第 6.5.17 章借用,C11 标准)

您可以像这样进行函数调用

  f(a, (t=3, t+2), c);

这里,(t=3, t+2)中的逗号是一个逗号运算符,这是有效的,可以接受。

但是,你不能写

  f(a, (t=3; t+2), c);

这是语法错误。

它确实有所作为的一种情况是:

while(foo(), bar()) {
    ...
}

我不知道这是否有任何实际用途,但它确实用逗号编译,但不是用分号编译。

如果

int x = 0, y = 0, z = 0 ;

, 不是 逗号运算符 但它们是逗号分隔符。
分号是语句和声明的一部分。

int i = 0;  // declaration
i = i + 5;  // statement

另一方面,逗号运算符是表达式的一部分。也就是说分号不能用在需要表达式的地方。例如

if(++i, i < 10) { /*...*/ }  // A semicolon can't be used.

逗号运算符已在其他答案中得到很好的讨论。仍然是 semi-colon.

semi-colon (;) 是一个语句终止符,意思是它终止任何语句的语法。这也意味着当表达式后跟 semi-colon 时,它会变成一个语句:

foo();                // a statement
bar();                // a statement
3+5;                  // a statement
(t=3, t+2);           // a statement
while(foo(), bar());  // a statement

while(foo(), bar()) {
    ;                 // empty statement
}

semi-colon 也终止声明。