Are non-local thread storage duration objects initialized to 0 in C?
static thread_local int x; // is x initialized to 0?
The C17 standard says the below (in 6.2.4.4).
An object whose identifier is declared with the storage-class specifier _Thread_local has thread storage duration. Its lifetime is the entire execution of the thread for which it is created, and its stored value is initialized when the thread is started.
It does not explicitly say it is initialized to 0. But the C standard makes it explicit and says: (in 3.6.2.2)
Variables with static storage duration ([basic.stc.static]) or thread storage duration ([basic.stc.thread]) shall be zero-initialized ([dcl.init]) before any other initialization takes place
So, does C initialize non-local thread_local objects to 0 or not?
CodePudding user response:
Thread local objects without explicit initialization are initialized to “zero.”
C 2018 7.26.1 3 says thread_local
expands to _Thread_local
if <threads.h>
is included. That is not shown in the question, but presumably it is.
C 2018 6.2.4 4 says “An object whose identifier is declared with the storage-class specifier _Thread_local
has thread storage duration…
C 2018 6.7.9 10 says:
… If an object that has static or thread storage duration is not initialized explicitly, then:
— if it has pointer type, it is initialized to a null pointer;
— if it has arithmetic type, it is initialized to (positive or unsigned) zero;
— if it is an aggregate, every member is initialized (recursively) according to these rules, and any padding is initialized to zero bits;
— if it is a union, the first named member is initialized (recursively) according to these rules, and any padding is initialized to zero bits;
The paragraph ends there; the trailing “;” instead of a period is a typographical error.
CodePudding user response:
Best practice: Initialize all variables. As much as the ISO specification says it is initialized or not, you depend on the compiler implementation. If your intention is to write portable software, set the initial value manually. If not, do exhaustive testing on the compiler you are using and understand what it is doing at every level of optimization. The quantity #ifdef clang, GNUC, _MSC_VER and etc in portable software gives a hint that trusting the specification is not a smart thing for the quality of your software.