rspec/rules/S5381/rule.adoc

45 lines
1.4 KiB
Plaintext
Raw Normal View History

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, R or (La)TeX.
2020-06-30 12:50:28 +02:00
2021-02-02 15:02:10 +01:00
This rule will flag uses of ``++^++`` in places where an exponentiation is suspected to be the intended operation, i.e on expressions that attempt to _xor_ 2 or 10 with a constant expression.
2020-06-30 12:50:28 +02:00
== Noncompliant Code Example
----
#include <stdint.h>
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
2020-06-30 12:50:28 +02:00
----
== Compliant Solution
----
#include <stdint.h>
#include <math.h>
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
----
== Exceptions
No issue will be raised when at least one of the operands is expressed as a binary, octal or hexadecimal literal. In such cases, the assumption is that _xor_ operation is intended.
2020-06-30 12:50:28 +02:00
----
#include <stdint.h>
uint32_t using_octal = 02 ^ 016; // Compliant
uint32_t using_binary = 0b10 ^ 9; // Compliant
uint32_t using_hex = 0xFF ^ 0x09; // Compliant
----
== See
* https://en.wikipedia.org/wiki/Exponentiation#In_programming_languages[Exponentiation on Wikipedia]