int main() {
std::cout << 1, std::cout << 2;
return 0;
}
The above snippet is syntactically correct, as commas can be used to separate statements. However,
int main() {
int a, std::string b;
return 0;
}
This returns with an error
Expected initializer before 'b'
Why is this? Is there some circumstances I cannot use a comma to separate statements? For example in this case definition of variables?
Commas never separate statements. Your first example is a single statement, consisting of an expression containing the comma operator. It happens to do the same thing as if you had written two statements std::cout << 1; std::cout << 2;
but they're not syntactically equivalent.
Likewise, your second example is (trying to be) a single declaration statement, and it's not a syntactically valid one. It is possible to use a comma (not as the comma operator)to separate two declarations of the same type int a, b;
with some variations such as int a, *b;
, but this is still one declaration statement.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With