Solarian Programmer

My programming ramblings

A Happy Halloween from C++ and an IIFE lambda

Posted on October 31, 2019 by Paul

Happy Halloween, from C++:

 1 // halloween.cpp
 2 #include <iostream>
 3 
 4 const auto dummy1 = [] {
 5     std::cout << "Hold my beer!\n";
 6     return 1;
 7 }();
 8 
 9 const auto dummy2 = [] {
10     std::cout << "Hold my second beer!\n";
11     return 2;
12 }();
13 
14 
15 int main() {
16     std::cout << "C++: Happy Halloween, your program starts here!\n";
17 }

Using an IIFE, or an “Immediately invoked function expression”, lambda to initialize a global variable can have surprising side effects:

% clang++ -std=c++17 -Wall -Wextra -pedantic halloween.cpp -o halloween
% ./halloween
Hold my beer!
Hold my second beer!
C++: Happy Halloween, your program starts here!
%

Because the global variables are initialized before the main is executed, the Hold my beer! and Hold my second beer! will be printed before the message from the main function is executed.

As a side note, on Windows, assuming that you have the MSVC compiler installed, you can build the above program with:

C:\DEV>cl /std:c++17 /W4 /EHsc halloween.cpp
C:\DEV>halloween
Hold my beer!
Hold my second beer!
C++: Happy Halloween, your program starts here!

C:\DEV>

Show Comments