【知识点】
为了简单直观,有的人喜欢将两条语句用逗号运算符隔开,写到一行。这在多数情况下,没有问题。但是,逗号运算符后不能和 return、break、continue 等连用。否则,就会报错:[Error] expected primary-expression before 'return'。
例如,下面语句就会报错:[Error] expected primary-expression before 'return'
if(x==0) cout<<"OK"<<endl,return;
这是因为,逗号运算符两边必须都是 Expressions(表达式),而上面代码中的 cout<<"OK"<<endl 是 expression statement(表达式语句),return 是 jump statements(跳转语句),所以报错。应该修改为:
if(x==0) {cout<<"OK"<<endl;return;
}
【官方解析】
● Expressions(表达式) ← https://en.cppreference.com/w/c/language/expressions
An expression is a sequence of operators and their operands, that specifies a computation.
● Statements(语句) ← https://en.cppreference.com/w/c/language/statements
Statements are fragments of the C program that are executed in sequence. The body of any function is a compound statement, which, in turn is a sequence of statements and declarations:
int main() {// start of a compound statementint n=1; // declaration (not a statement)n=n+1; // expression statementprintf("n=%d\n",n); // expression statementreturn 0; // return statement
} // end of compound statement, end of function body
● Comma operator(逗号运算符) ← https://en.cppreference.com/w/c/language/operator_other
The comma operator expression has the form
lhs , rhs
where
lhs - any expression
rhs - any expression other than another comma operator (in other words, comma operator's associativity is left-to-right)