Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ weird expressions are compiled just fine

Tags:

c++

Why are the following valid C++ expressions? These aren't lambdas

[]{}(); {}[]{}; 

Can someone explain them to me?

like image 570
Dean Avatar asked Jun 20 '16 12:06

Dean


2 Answers

The first is a lambda with no parameter list and a subsequent call. []{} is equivalent to [](){} so the whole line is equivalent to

[](){}(); 

The second is a pair of braces, which introduce and then immediately close a scope, followed by an unused lambda definition with no parameter list:

{   // empty scope } []{}; // lambda 

You can refer to http://en.cppreference.com/w/cpp/language/lambda for the variations on lambda definition syntax.

like image 71
Andrew Avatar answered Sep 28 '22 02:09

Andrew


  • This one is a lambda call

    []{}(); 

    it is equivalent to

    [](){}(); 
  • The second is an empty scope, followed by a (unused) lambda.

Parens are optional for lambda without parameter.

like image 36
Jarod42 Avatar answered Sep 28 '22 02:09

Jarod42