rspec/rules/S5381/cfamily/rule.adoc
2023-10-05 15:02:59 +02:00

68 lines
1.8 KiB
Plaintext

== 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
[source,cpp]
----
#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
----
=== Compliant solution
[source,cpp]
----
#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
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.
[source,cpp]
----
#include <stdint.h>
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
----
== Resources
* Wikipedia - https://en.wikipedia.org/wiki/Exponentiation#In_programming_languages[Exponentiation: In programming languages]
* Wikipedia - https://en.wikipedia.org/wiki/Exclusive_or[Exclusive or (xor)]
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
=== Message
Make sure that this use of "^" is intended
=== Highlighting
Whole expression
endif::env-github,rspecator-view[]