Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ syntax question - Why can't I use comma to separate variable definition of different types

Tags:

c++

syntax

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?

like image 523
Learning Mathematics Avatar asked Dec 12 '20 05:12

Learning Mathematics


1 Answers

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.

like image 96
Nate Eldredge Avatar answered Nov 08 '22 04:11

Nate Eldredge