...
The intent of the expression in this noncompliant code example is to test the least significant bit of x
.
Code Block |
---|
x & 1 == 0 |
Because of operator precedence rules, the expression is parsed asx & as
Code Block |
---|
x & (1 == 0) |
which evaluates to
Code Block |
---|
(x & 0) |
and then to 0
.
Compliant Solution
In this compliant solution, parentheses are used to ensure the expression evaluates as expected.
Code Block |
---|
(x & 1) == 0 |
Exceptions
EXP00-EX1: Mathematical expressions that follow algebraic order do not require parentheses. For instance, in the expressionx + y * zexpression
Code Block |
---|
x + y * z
|
the multiplication is performed before the addition by mathematical convention. Consequently, parentheses to enforce this would be redundant.
Code Block |
---|
x + (y * z) |
Risk Assessment
Mistakes regarding precedence rules may cause an expression to be evaluated in an unintended way. This can lead to unexpected and abnormal program behavior.
...