![]() |
![]() |
3427 | ![]() |
||||
![]() | |||||||
| Redundancy | |||||||
The right hand operand of this logical AND (&&) or OR (||) operator does not generate side effects and the result of the operation is never not used. The operand is therefore a redundant expression. The right hand operand of a logical AND (&&) operator is only evaluated if the left hand operand evaluates to "true", i.e. non-zero. Similarly the right hand operand of a logical OR (||) operator is only evaluated if the left hand operand evaluates to "false", i.e. zero. In either case, this property is not relevant unless the right hand operand generates side effects. Many coding standards do not allow side effects in the right hand operand for precisely this reason, but it is possible to make deliberate use of this behaviour. For example, it is possible to construct statements in which the logical operators are effectively used to control the conditional execution of side.effects in the right hand operand. However if the logical value resulting from the operator is not used and the right hand operand does not generate side.effects, it is effectively a redundant expression. For example:
/*PRQA S 2017,3200,3208,3227,3398,3408,3415,3416,3440,3447,4109 ++*/
extern int f1(int p);
extern void foo(int a, int b, int c)
{
/* EXAMPLE 1 */
(a > 0) && (++a);
/* This is equivalent to the following */
if (a > 0)
{
++a;
}
/* EXAMPLE 2 */
(a > 0) && f1(a) && f1(b) && f1(c);
/* This is equivalent to the following */
if (a > 0)
{
if (f1(a) != 0)
{
if (f1(b) != 0)
{
f1(c);
}
}
}
/* EXAMPLE 3 */
(a > 0) && f1(a) && f1(b) && c; /* Message 3427 */
/* This is equivalent to the following */
if (a > 0)
{
if (f1(a) != 0)
{
if (f1(b) != 0)
{
c; /* Message 3112 - no side effects */
}
}
}
}
![]() | ||
| QA·C Source Code Analyser 8.1.2
© 2013 Programming Research. www.programmingresearch.com | Personality Groups | Glossary | Message Index | Contents |