CKTIS / C
atomic_fetch_xor — C23 atomic generic function
`atomic_fetch_xor(object, operand)` from `<stdatomic.h>` atomically performs `*object ^= operand` on an atomic integer type and returns the value from before the bits were toggled. It is one read-modify-write operation.
Version: C23
Syntax
C atomic_fetch_xor(volatile A *object, M operand);atomic_fetch_xor(object, operand) from <stdatomic.h> atomically performs *object ^= operand on an atomic integer type and returns the value from before the bits were toggled. It is one read-modify-write operation.
Use it to toggle exactly selected bits of shared state atomically. The example really XORs 0xA with 0x6: it returns old value 10, and the new 0xC pattern has value 12.
The function does not support atomic pointers; the non-_explicit form uses memory_order_seq_cst and need not be lock-free. XOR toggles rather than records an event: two calls with the same mask restore the previous state, so two reports can cancel each other. The mask must have the intended width and signedness. The supported atomic integer types explicitly exclude _Atomic bool; this operation has no pointer form.
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_uint flags = 0xAu;
unsigned previous = atomic_fetch_xor(&flags, 0x6u);
printf("%u %u\n", previous, atomic_load(&flags));
return 0;
}
Result
10 12
Use it to toggle exactly selected bits of shared state atomically. The example really XORs `0xA` with `0x6`: it returns old value `10`, and the new `0xC` pattern has value `12`.