How is “int main(){(([](){})());}” valid C++?

后端 未结 1 883
别那么骄傲
别那么骄傲 2021-01-29 17:49

I recently came across the following esoteric piece of code.

int main(){(([](){})());}

Reformat it as follows to make it more readable:

1条回答
  •  闹比i
    闹比i (楼主)
    2021-01-29 18:30

    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)).

    0 讨论(0)
提交回复
热议问题