简体   繁体   中英

How to initialize and use a C11 _Atomic variable?

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 technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM