fork(1) download
  1. #include<iostream>
  2.  
  3. #define CONCATE_(X,Y) X##Y
  4. #define CONCATE(X,Y) CONCATE_(X,Y)
  5. #define UNIQUE(NAME) CONCATE(NAME, __LINE__)
  6.  
  7. struct Static_
  8. {
  9. template<typename T> Static_ (T lambda) { lambda(); }
  10. ~Static_ () {} // to counter unused variable warning
  11. };
  12.  
  13. #define STATIC static Static_ UNIQUE(block) = [&]() -> void
  14.  
  15. void foo ()
  16. {
  17. std::cout << "foo()\n";
  18. STATIC
  19. {
  20. std::cout << "Executes only once inside foo()\n";
  21. };
  22. }
  23.  
  24. int main ()
  25. {
  26. std::cout << "main()\n";
  27. foo();
  28. foo();
  29. foo();
  30. }
  31.  
  32. STATIC
  33. {
  34. std::cout << "Executes only once before main()\n";
  35. };
  36.  
Success #stdin #stdout 0s 3456KB
stdin
Standard input is empty
stdout
Executes only once before main()
main()
foo()
Executes only once inside foo()
foo()
foo()