Skip to content

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

Open
@richelbilderbeek

Description

@richelbilderbeek

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

Metadata

Metadata

Labels

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions