Why is this an issue?
In C and its family of languages, the
^ operator performs the exclusive or (xor) operation. This can be misleading since
^ is also commonly used to designate the exponentiation operation, for instance, in BASIC or R.
This rule will flag uses of
^ in places where exponentiation is suspected to be the intended operation, i.e., on expressions that
attempt to xor 2 or 10 with a constant expression.
Noncompliant code example
uint32_t max_uint16 = 2 ^ 16; // Noncompliant: expression evaluates to 18, instead of the intended 65536
uint32_t one_billion = 10 ^ 9; // Noncompliant: expression evaluates to 3 instead of the intended 1e9
uint32_t max_uint16 = 1 << 16; // Compliant: using left shift to generate a power of 2
uint32_t one_billion = pow(10, 9); // Compliant: using the math pow function
The rule does not raise an issue when at least one of the operands is expressed as a binary, octal, or hexadecimal literal. The assumption is that
the xor operation is intended in such cases.
uint32_t using_octal = 02 ^ 016; // Compliant by exception
uint32_t using_binary = 0b10 ^ 9; // Compliant by exception
uint32_t using_hex = 0xFF ^ 0x09; // Compliant by exception