CKTIS / C
atomic_compare_exchange_strong — C23 atomic generic function
`atomic_compare_exchange_strong(object, expected, desired)` from `<stdatomic.h>` atomically compares atomic `*object` with non-atomic `*expected`. If equal it stores `desired` in the object and returns `true`; otherwise it writes the object’s current value to `*expected` and returns `false`, without spurious failure.
Version: C23
Syntax
bool atomic_compare_exchange_strong(volatile A *object, C *expected, C desired);atomic_compare_exchange_strong(object, expected, desired) from <stdatomic.h> atomically compares atomic *object with non-atomic *expected. If equal it stores desired in the object and returns true; otherwise it writes the object’s current value to *expected and returns false, without spurious failure.
Use it for a one-shot state transition whose success and genuine mismatch take separate paths. The example performs a successful 7→11 replacement, then tries again expecting 7; that second attempt fails and updates expected to 11.
object must point to a compatible atomic type, while expected must point to a modifiable corresponding non-atomic type; invalid pointers or a race on expected are erroneous. The non-_explicit form uses memory_order_seq_cst. Comparing only the value does not solve ABA or protect other shared data without a correct memory-order protocol. Violating the pointer requirements—including an invalid pointer, an incompatible pointed-to type, or a nonmodifiable expected object—has undefined behavior; an unsynchronized race on expected likewise has undefined behavior.
C23 compares the contents, that is, the value representations designated by object and expected, rather than only their mathematical equality; the atomic read-modify-write applies to object, while expected is ordinary non-atomic storage. Concurrent unsynchronized access to expected creates a data race and undefined behavior. 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 <stdbool.h>
#include <stdio.h>
int main(void) {
atomic_int value = 7;
int expected = 7;
bool replaced = atomic_compare_exchange_strong(&value, &expected, 11);
expected = 7;
bool rejected = atomic_compare_exchange_strong(&value, &expected, 13);
printf("%d %d %d %d\n", replaced, rejected, atomic_load(&value), expected);
return 0;
}
Result
1 0 11 11
Use it for a one-shot state transition whose success and genuine mismatch take separate paths. The example performs a successful `7→11` replacement, then tries again expecting `7`; that second attempt fails and updates `expected` to `11`.