CKTIS / C++
Bitwise AND assignment (&=)
The &= operator performs bitwise AND and stores the result in its left operand. It keeps only bits that were set in both operands. A common use is retaining selected bits with a mask.
Version: C++23; repository compiler flag, production runtime not attested
Syntax
lhs &= rhsThe built-in operator lhs &= rhs computes bitwise AND and stores the result in lhs. At each position, the result bit is 1 only when both corresponding operand bits are 1. A mask therefore preserves bits selected by ones and clears positions selected by zeros.
Its behavior corresponds to lhs = lhs & rhs, except that the expression lhs is evaluated only once. The left operand must be a modifiable lvalue of integral type; it cannot be constant. The right operand can have integral or unscoped enumeration type. The usual arithmetic conversions, including applicable integral promotions, occur before the operation, and the result is converted to the left operand's type before storage.
The right operand is evaluated before the left operand. The whole expression yields an lvalue referring to the modified left operand. Do not confuse &= with logical &&: &= does not short-circuit. For masks, prefer matching unsigned types to reduce conversion surprises.
In the example, flags has binary value 1101 and mask has value 1010. After flags &= mask, the remaining value is 1000, or decimal 8. This explanation concerns the built-in operator; an overloaded operator&= for a class type can define different behavior.
Examples
#include <iostream>
int main() {
unsigned int flags = 0b1101u;
const unsigned int mask = 0b1010u;
flags &= mask;
std::cout << flags << '\n';
}
Result
8
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.