patterncppCritical
How is "int main(){(([](){})());}" valid C++?
Viewed 0 times
mainhowvalidint
Problem
I recently came across the following esoteric piece of code.
Reformat it as follows to make it more readable:
But I can't get my head around how
Google didn't help much with this all-symbol search. But it compiles in Visual Studio 2010 and outputs nothing. There were no errors, and no warnings. So it looks like valid code.
I've never seen any valid code that is so bizarre outside of Javascript and C function pointers.
Can someone explain how this is valid C++?
int main(){(([](){})());}Reformat it as follows to make it more readable:
int main(){
(([](){})()); // Um... what?!?!
}But I can't get my head around how
(([](){})()) is valid code.- It doesn't look like function pointer syntax.
- It can't be some operator overloading trick. The code compiles as is.
Google didn't help much with this all-symbol search. But it compiles in Visual Studio 2010 and outputs nothing. There were no errors, and no warnings. So it looks like valid code.
I've never seen any valid code that is so bizarre outside of Javascript and C function pointers.
Can someone explain how this is valid C++?
Solution
The code essentially calls an empty lambda.
Let's start from the beginning:
Then, in C and C++, you can wrap expressions in parens and they behave exactly the same† as if written without them, so that's what the first pair of parens around the lambda does. We're now at
Then,
The whole expression is wrapped in parens again and we get
At last,
† There are some corner cases at least in C++, like with
Let's start from the beginning:
[](){} is an empty lambda expression.Then, in C and C++, you can wrap expressions in parens and they behave exactly the same† as if written without them, so that's what the first pair of parens around the lambda does. We're now at
([](){}).Then,
() after the first wrapping parens calls the (empty) lambda. We're now at ([](){})()The whole expression is wrapped in parens again and we get
(([](){})()).At last,
; ends the statement. We arrive at (([](){})());.† There are some corner cases at least in C++, like with
T a_var; there's a difference between decltype(a_var) and decltype((a_var)).Context
Stack Overflow Q#13603286, score: 298
Revisions (0)
No revisions yet.