Is the following code allowed?
_Atomic(unsigned int) a = 1;
if (a == 0) {
}
The C11 spec (n1570) says at 6.3.2.1p2:
if the lvalue has atomic type, the value has the non-atomic version of the type of the lvalue.
So this seems to say it's ok.
Is the following code allowed?
_Atomic(unsigned int) a = 1;
if (a == 0) {
}
The C11 spec (n1570) says at 6.3.2.1p2:
if the lvalue has atomic type, the value has the non-atomic version of the type of the lvalue.
So this seems to say it's ok.
No, initialization like that is not ok. You'd have to use ATOMIC_VAR_INIT
to initialize an atomic object. From C11 7.17.2.1:
The ATOMIC_VAR_INIT macro expands to a token sequence suitable for initializing an atomic object of a type that is initialization-compatible with value. An atomic object with automatic storage duration that is not explicitly initialized using ATOMIC_VAR_INIT is initially in an indeterminate state; however, the default (zero) initialization for objects with static or thread-local storage duration is guaranteed to produce a valid state.
Otherwise the object would be in a valid state, but "indeterminate" so you wouldn't know which value it has.
The state of this has changed with C17 which removed the requirement to initialize with ATOMIC_VAR_INIT
. Now doing an initialization as presented in the question is ok and the right way to go.
As someone suggested, another possibility is still to do a dynamic initialization with atomic_init
, but classic initialization is certainly to be preferred wherever you may.