CKTIS / C
atomic_fetch_add — C23 atomic generic function
`atomic_fetch_add(object, operand)` from `<stdatomic.h>` atomically adds `operand` to an atomic integer or pointer object and returns the value from before the addition. It is one read-modify-write operation.
Version: C23
Syntax
C atomic_fetch_add(volatile A *object, M operand);atomic_fetch_add(object, operand) from <stdatomic.h> atomically adds operand to an atomic integer or pointer object and returns the value from before the addition. It is one read-modify-write operation.
Use it to allocate unique sequence numbers or increment a shared counter without lost updates. The example actually adds 3 to 10: the returned old ticket is 10, and the state after the operation is 13.
The non-_explicit form uses memory_order_seq_cst, but the operation need not be lock-free. For atomic integer types signed arithmetic is defined to use two’s-complement representation with no undefined overflow result; for an atomic pointer the operand is ptrdiff_t and the result may be an invalid address. The return is always the old value. The term “atomic integer type” explicitly excludes _Atomic bool; the separately specified atomic-pointer form remains permitted.
This generic function name may be a macro or an external identifier; suppressing the macro to call an actual function, or defining an external identifier with that name, has undefined behavior.
Examples
#include <stdatomic.h>
#include <stdio.h>
int main(void) {
atomic_int tickets = 10;
int previous = atomic_fetch_add(&tickets, 3);
printf("%d %d\n", previous, atomic_load(&tickets));
return 0;
}
Result
10 13
Use it to allocate unique sequence numbers or increment a shared counter without lost updates. The example actually adds `3` to `10`: the returned old ticket is `10`, and the state after the operation is `13`.