CKTIS / C
atomic_fetch_sub — C23 atomic generic function
`atomic_fetch_sub(object, operand)` from `<stdatomic.h>` atomically subtracts `operand` from an atomic integer or pointer object and returns the value from before the subtraction. It is one read-modify-write operation.
Version: C23
Syntax
C atomic_fetch_sub(volatile A *object, M operand);atomic_fetch_sub(object, operand) from <stdatomic.h> atomically subtracts operand from an atomic integer or pointer object and returns the value from before the subtraction. It is one read-modify-write operation.
Use it to decrease a shared counter without lost updates when the old value is needed for a decision. The example actually subtracts 6 from 20: it returns previous value 20, and the state after the operation is 14.
The non-_explicit form uses memory_order_seq_cst and need not be lock-free. It does not saturate at zero: signed atomic integer arithmetic uses two’s-complement representation without undefined overflow, while unsigned arithmetic wraps modulo; for an atomic pointer the operand is ptrdiff_t and the result may be an invalid address. 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 remaining = 20;
int previous = atomic_fetch_sub(&remaining, 6);
printf("%d %d\n", previous, atomic_load(&remaining));
return 0;
}
Result
20 14
Use it to decrease a shared counter without lost updates when the old value is needed for a decision. The example actually subtracts `6` from `20`: it returns previous value `20`, and the state after the operation is `14`.