3

Boiling a problem I'm having down to its essence, I can initialize a variable as an int by first executing a do-nothing lambda in a comma expression like this:

int main(){
  auto x = ( []{}(), 10 );          // same effect as auto x = 10;
}

But if I don't parenthesize the initializing expression,

int main(){
  auto y = []{}(), 10;              // won't compile
}

all of gcc, clang, and MSVC complain about trying to initialize y with a void expression.

Why do I have to parenthesize the comma expression to use it as an initializer?

6
  • "Boiling a problem I'm having down ..." Sounds like you have a XY-problem. Do you need the side effect of the lambda expression before x is initialized actually? Feb 4, 2016 at 17:33
  • 1
    Yes. I want to execute a static_assert before computing the expression to be used in a member initialization list to initialize a class data member. Feb 4, 2016 at 17:36
  • Well, static_assert is executed at compile time anyways. I don't think it's actually necessary to put it inside a lambda expression. Feb 4, 2016 at 17:39
  • I need the static_assert to be evaluated before the initializing expression, because if the static_assert fails, the initializing expression will lead to a really horrible template instantiation error message. The purpose of the static_assert is to generate a good error message instead. Feb 4, 2016 at 17:43
  • What's wrong with auto x = []{ return 10; }(); ? Much clearer.
    – MSalters
    Feb 4, 2016 at 23:02

1 Answer 1

5

In a declaration, the , symbol separates declarators. A simpler example:

int i = 2, j = 3;     // OK: declares `i` and `j`
int i = 2, 3;         // Error: `3` is not a declarator

In the second case, it looks ambiguous. Is the , separating declarators, or is the , part of an expression 2, 3?

To resolve this ambiguity we can consult the language grammar (C++14 [dcl.decl]):

simple-declaration:
    decl-specifier-seqopt init-declarator-listopt ;
    attribute-specifier-seq decl-specifier-seqopt init-declarator-list ;

init-declarator-list:
    init-declarator
    init-declarator-list , init-declarator

init-declarator:
    declarator initializeropt

The way grammars work, this means that when parsing a declaration the longest possible sequence that matches init-declarator , is considered. (This is sometimes called "maximum munch principle"). So int i = 2, matches init-declarator , . Then 3 fails to match init-declarator, so parsing fails.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.