Skip to content

Commit

Permalink
Modify rule S6228: reword and add documentation link
Browse files Browse the repository at this point in the history
  • Loading branch information
amelie-renard-sonarsource committed Oct 5, 2023
1 parent a5ce9d9 commit d324d16
Showing 1 changed file with 8 additions and 6 deletions.
14 changes: 8 additions & 6 deletions rules/S6228/cfamily/rule.adoc
Original file line number Diff line number Diff line change
@@ -1,20 +1,20 @@
== Why is this an issue?

Since integers are usually represented in binary form in computers, it is efficient to check if a given number is a power of two by checking if its ``++unsigned++`` representation has a single bit set.
Since integers are usually represented in binary form in computers, it is efficient to check if a given number is a power of two by checking if its ``++unsigned++`` representation has a single-bit set.


In {cpp} such check could be expressed as ``++x & (x-1) == 0++``. However, the intent of this expression is unclear. Furthermore, it requires to take special care for the value ``++0++``, which would pass the above check, while not having any bit set and not being a power of two.
In {cpp} such check could be expressed as ``++x & (x-1) == 0++``. However, the intent of this expression is unclear. Furthermore, it requires special care for the value ``++0++``, which would pass the above check without having any bit set or being a power of two.


This check can be expressed more clearly with the ``++std::has_single_bit++`` function template, introduced in {cpp}20.
The ``++std::has_single_bit++`` function template, introduced in {cpp}20 that checks if an integer is a power of two, expresses the intent more clearly.


This rule reports computations that could be replaced with ``++std::has_single_bit++`` .
This rule reports computations that could be replaced with ``++std::has_single_bit++``.


=== Noncompliant code example

[source,cpp]
[source,cpp,diff-id=1,diff-type=noncompliant]
----
void f(unsigned x) {
if ((x > 0) && !(x & (x-1))) { // Noncompliant
Expand All @@ -27,7 +27,7 @@ void f(unsigned x) {

=== Compliant solution

[source,cpp]
[source,cpp,diff-id=1,diff-type=compliant]
----
void f(unsigned x) {
if (std::has_single_bit(x)) {
Expand All @@ -37,4 +37,6 @@ void f(unsigned x) {
}
----

== Resources

* {cpp} reference - https://en.cppreference.com/w/cpp/numeric/has_single_bit[std::has_single_bit]

0 comments on commit d324d16

Please sign in to comment.