Are atomic operations on non-atomic types in C atomic?

Viewed 67

The C17 standard specifies a list of atomic operations. For example, an atomic read-write-modify operation on an atomic object of type A is defined in the standard as:

C atomic_fetch_add(volatile A *object, M operand);

But we can call atomic_fetch_add on non-atomic types:

static int x;
static int foo(void *arg) {
  atomic_fetch_add(&x, 3);
}

My question: is the above atomic_fetch_add operation on the non-atomic object x guaranteed to be atomic?

1 Answers

on an atomic object of type A is defined in the standard

But we can call

GCC will accept it. But on clang you'll get an error.

is the above atomic_fetch_add operation on the non-atomic object x guaranteed to be atomic?

No. In the standard the behavior of the code you presented is not defined, there is no guarantee of any kind. From https://port70.net/~nsz/c/c11/n1570.html#7.17 :

5 In the following synopses:

  • An A refers to one of the atomic types. [...]

And then all the functions are defined in terms of A, like in https://port70.net/~nsz/c/c11/n1570.html#7.17.7.5p2 :

C atomic_fetch_key(volatile A *object, M operand);

Atomic type is a type with _Atomic.

Related