I recently came across the following esoteric piece of code.
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.
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++?
No. It's non-standard. The standard prototype of main is int main() with the optional command line arguments argc and argv . The int returned by main() is a way for a program to return a value to the system that invokes it.
int main represents that the function returns some integer even '0' at the end of the program execution. '0' represents the successful execution of a program. int main(void) represents that the function takes NO argument.
The void main() indicates that the main() function will not return any value, but the int main() indicates that the main() can return integer type data. When our program is simple, and it is not going to terminate before reaching the last line of the code, or the code is error free, then we can use the void main().
The code essentially calls an empty lambda.
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))
.
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