This code: []() -> char { return '\0'; }()
is an expression which calls an unnamed lambda function. In fact it contains some redundant elements and could have been written []{ return '\0'; }()
. Since empty argument list in lambdas can be omitted, and the return type can be deduced from the expression in the return
statement.
The code is very similar to:
char qux() { return '\0'; }
char __ = qux();
except that there is no need for the identifier qux
and therefore reduced chance of collision with some other identifier the program uses.
Naming the variable __
causes undefined behaviour since names containing double-underscore are reserved to the implementation, it'd be better for this code to use some valid identifier and that can perhaps be hidden via an unnamed namespace if there is a collision.
The purpose of this code is to execute the function body before main()
runs. It would be cleaner to have this code occur on the first line of main()
, but perhaps the author was concerned that there might be some other code which also runs before main()
and relies on these statements having executed.
However, this method does not really resolve the problem as if said other statements are in a different translation unit, there is no guarantee of __
's initialization occurring before the other unit's static initialization. See static initialization order fiasco.