isocpp / isocpp/CppCoreGuidelines

Suggestion: ES.63: Distinguish between logical and bitwise comparison

Open
#502 6 comments 0 reactions 1 assignee View on GitHub

@BjarneStroustrup is already working on this.

Since Feb 1, 2016.

open
Dominant language
CSS
Stars
45.3k
Forks
5.6k
PR merge metrics
No merged PRs in 30d

Description

Edit: Added text to Exceptions section, due to @BjarneStroustrup's comment

ES.63: Distinguish between logical and bitwise comparison

Reason:

Say what you mean. If you want both the first and second term to be true, use operator&&. If you want to match bitflags, use operator&.

Matching bitflags can only be done sensibly using operator&, where doing a logical comparison can be done using one and two ampersands. In this case, use operator&&. There is no run-time speed to be gained using operator& instead.

The same story applies to operator| and operator||.

Examples:

Both terms being some value:

if (a == 42 && b == 3.14) { /* */ } //OK
if (a == 42 & b == 3.14) { /* */ } //Bad, will give compiler warning
if ((a == 42) & (b == 3.14)) { /* */ } //Bad, say what you mean

Bitflag:

if (i & flag_is_visible) { /* draw */ } //OK
if (i && flag_is_visible) { /* draw */ } //Runtime error

Alternatives: none

Exceptions:

If you don't need the order dependence of && and you've measured that & is a significant performance optimization. If this is the case, it should be marked as an optimization. One way to do so is by making it an inline function, e,g, fast_and(0<=a,a<max).

Enforcement: compilers already give warnings

See alsos: none

Notes:

I saw the a == 42 & b == 3.14 in the wild, that's why I suggested this rule, as the current guidelines do not state the preferred form explicitly yet.

Discussion:

Perhaps this item would better be renamed to a Non-Rule: NR x: operator& does not outperform operator&& in runtime performance

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.