4

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.

Ciro Santilli OurBigBook.com
  • 347,512
  • 102
  • 1,199
  • 985
joey
  • 578
  • 4
  • 10
  • Perhaps this question is your answer: http://stackoverflow.com/questions/10668941/c11-grammar-ambiguity-between-atomic-type-specifier-and-qualifier – Tony The Lion Mar 10 '13 at 01:02
  • ISO/IEC 9899:2011 §6.7.2.4 _Atomic type specifiers_ indicates that your declaration is probably OK. §6.7.4 _Type qualifiers_ includes an example: `_Atomic volatile int *p;` without the parentheses, so the parentheses are not always necessary. – Jonathan Leffler Mar 10 '13 at 01:09
  • Well, it's more the reference to "a", whether that's an ok way to load the atomic value. – joey Mar 10 '13 at 01:16
  • AFAICT, yes — but I've not actually tried it...have you got a C11 compiler to try it on? – Jonathan Leffler Mar 10 '13 at 04:30
  • The C11 compiler crashed, hence the question! :) – joey Mar 10 '13 at 23:09

1 Answers1

7

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.

Jens Gustedt
  • 76,821
  • 6
  • 102
  • 177