Get the latest tech news

C++: Zero-cost static initialization


"Усердие все превозмогает!" К. Прутков, Мысли и афоризмы, I, 84 In C and C++ a static variable can be defined in a function scope: int foo() { static int counter = 1; printf("foo() has been called %i times.\n", counter++); ...

For C this question is vacuous, because the initialiser must be a compile-time constant, so the actual value of the static object is embedded in the compiled binary and is always valid. It is clear that the compiler must add some sort of an internal flag to check whether the initialisation has already been performed and some synchronisation object to serialise concurrent calls to foo()[ godbolt]: For some time I thought that it is, but then I realised that there is another way to specify the section in which the variable is located: the.pushsection directive of the embedded assembler (do not be afraid, we will use only portable part).

Get the Android app

Or read this on Hacker News

Read more on:

Photo of C++

C++

Related news:

News photo

C++: Maps on Chains

News photo

Jank is C++

News photo

No More Shading Languages: Compiling C++ to Vulkan Shaders [pdf]