12

The C17 standard deprecates ATOMIC_VAR_INIT from stdatomic.h, meaning it still supports it but would rather it not be used. What is the correct non-deprecated way of initializing atomics in C17?

Same as non-atomic types:

atomic_int foo = 42;

Or something new?

Wingblade
  • 9,585
  • 10
  • 35
  • 48
  • The [ISO C working group website](http://www.open-std.org/jtc1/sc22/wg14/) dosn't contain any information about a C17 standard. Do you mean C++? – s7amuser Apr 09 '18 at 10:56
  • 2
    Looking at the corresponding defect report ([DR 485](http://www.open-std.org/jtc1/sc22/wg14/www/docs/n2148.htm#dr_485)) I would say that your example is correct (though I don't know enough about the standard to be sure) – UnholySheep Apr 09 '18 at 11:32
  • 1
    @s7amuser No I mean C. Apparently C17 is a minor revision to the C11 standard rather than a whole new standard, which may be why it isn't listed as a standard. – Wingblade May 21 '18 at 12:02

2 Answers2

11

C17 makes it ok to initialize atomics using the usual explicit initialization:

atomic_int n = 42;

C17 literally just dropped the two words "using ATOMIC_VAR_INIT" from the sentence in 7.17.2.1.

Cubbi
  • 46,567
  • 13
  • 103
  • 169
3

Based on that document, section DR 454, using the macro makes it impossible to know in which state is the variable.

atomic_int guide1 = ATOMIC_VAR_INIT(42); /* known value(42); WHAT STATE? */

But using the normal assignment is also undetermined, as shown bellow.

atomic_int guide2;        /* indeterminate value; indeterminate state */
atomic_int guide3 = 42;   /* known value(42); indeterminate state */

To put your variable in a known state, you have either to use static or the atomic_init function.

static atomic_int guide4;  /* known value(0); valid state */
static atomic_int guide5 = 42; /* known value(42); valid state */
atomic_int guide6;
atomic_init(&guide6, 42); /* known value(42); initialized state */

But that's the only information I could find.

informaticienzero
  • 1,796
  • 1
  • 12
  • 22