MISRA Discussion Forums

Full Version: Rule 12.5: OR sequence without parentheses not compliant?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hello,

I have a question regarding Rule 12.5: "The operands of a logical && or || shall be primary-expressions."

I often use constructs of the form "(condition1) || (condition2) || ... || (condition n)" to test for illegal values of a set of input parameters in functions (see example below), which should be compliant as far as I understand the rule text without the need of extra parentheses to group the conditions (parenthesised expression, sequence of only logical ||). However, my analysis tool (flexelint, v9.00e) complains about this construct ("non-primary expression"). Did I got something wrong about the definition of "primary expression" or is this a false positive?

Thanks in advance for any answers.

Example:

Code:
if ((start >= end) || (start > 7U) || (end > 8U))      /* raises rule violation */
{
    /* do something */
}
else
{
    /* do something different*/
}


if ((start >= end) || ((start > 7U) || (end > 8U)))      /* does not raise violation, note extra parentheses around second and third condition */
{
    /* do something */
}
else
{
    /* do something different*/
}
It is my understanding that Rule 12.5 allows exceptions if the operands are "effectively Boolean"
So you first example is allowed as the expression (start >= end) || (start > 7U) is effectively Boolean.
As indeed is the expression (start > 7U) || (end > 8U)
So which ever way you look at it, it will be allowed under rule 12.5.
The last sentence of the first paragraph of Rule 12.5 reads:
Quote:Where an expression consists of either a sequence of only logical && or a sequence of only logical || , extra parentheses are not required.

Therefore the code is compliant with Rule 12.5.

Your tool appears to be checking correctly against the headline rule (the extra parentheses make the right operand of the first || into a primary expression) but has not taken the whole text of the rule into account.
Hello,

Rule 12.1 explicitly mentions C's operator precedence in expressions.
Rule 12.5 is a special case of rule 12.1.

What about compiler switches or preprocessor statements?

#if !defined(__cplusplus) || defined(__STDC_LIMIT_MACROS)

are braces (parentheses) required here? (found in vendor header files)

Thanks in advance
Yes, the rule applies to preprocessing expressions in exactly the same way as it would to other expressions.

Since the defined operator is a unary operator, it will need parentheses, in much the same way as a function call would require parentheses in a non-preprocessing expression. So, the example would need to be written:

Code:
#if (!defined(__cplusplus)) || (defined(__STDC_LIMIT_MACROS))