C++语法问题-为什么我不能用逗号来分隔不同类型的变量定义
int main() {
std::cout << 1, std::cout << 2;
return 0;
}
上面的代码片段在语法上是正确的,因为逗号可用于分隔语句。然而,
int main() {
int a, std::string b;
return 0;
}
这会返回一个错误
'b' 之前的预期初始化程序
为什么是这样?在某些情况下我不能使用逗号分隔语句吗?例如在这种情况下定义变量?
回答
逗号从不分隔语句。您的第一个示例是单个语句,由包含逗号运算符的表达式组成。它恰好做同样的事情,就像你写了两个语句,std::cout << 1; std::cout << 2;但它们在语法上并不相同。
同样,你的第二个例子是(试图成为)一个单一的声明语句,它在语法上不是有效的。可以使用逗号(而不是逗号运算符)来分隔int a, b;具有一些变体的相同类型的两个声明,例如int a, *b;,但这仍然是一个声明语句。
- @LearningMathematics: **Any** two expressions can be the operands of the comma operator. See the link I gave above, or https://www.fluentcpp.com/2018/07/31/how-to-get-along-with-the-comma-operator/ for a briefer introduction. It's a general fact about C++: binary operators take two operands, each of which is an expression, and the combination of `expression operator expression` is itself an expression. This sort of recursive definition is fundamental in understanding programming language syntax.