Page 1 of 1

Doubt on rule 13.2

Posted: Mon Feb 16, 2009 1:01 pm
by roberto
One of the examples given for rule 13.2 is:

Code: Select all

if ( y ) /* Not compliant, unless y is effectively Boolean data
                              (e.g. a flag) */
Would it still be not compliant if y is of pointer type?
In case it is compliant, should 13.2 be interpreted as to be applicable only to expressions of integral type?

Re: Doubt on rule 13.2

Posted: Thu Feb 19, 2009 2:01 pm
by Lundin
The rule says "tests of a value against zero". As I understand it, this applies to everything that isn't Boolean: integers, pointers, float numbers, strings...

Pointers are especially troublesome, since they aren't always containing address 0, but could also contain the mysterious address NULL, which could be defined as 0 or (void*)0. Using an implicity comparison can therefore cause your compiler to whine about implicit typecasting.

It is generally considered good programming practice to explicitly compare pointers against NULL, no matter what MISRA advises regarding implicit tests against zero.

Re: Doubt on rule 13.2

Posted: Fri Feb 20, 2009 4:11 pm
by roberto
Hi Lundin,

in this moment I am not concerned about good programming practice, but on the genuine interpretation of MISRA rules.
In particular, when y is a pointer,

Code: Select all

  if ( y ) ...
is not testing a value against zero: it is testing the validity of a pointer and, as you write, this may have nothing to do with zero.
This reasoning made me think that, perhaps, there is an oversight in the example given on page 65 of MISRA-C:2004: perhaps it should read

Code: Select all

  if ( y ) /* Not compliant, unless y is effectively Boolean data
               (e.g. a flag) or a pointer.  */
Can the MISRA committee shed some light on this?


Re: Doubt on rule 13.2

Posted: Mon Feb 23, 2009 11:14 am
by Lundin
But you are testing against zero, rather than NULL. The difference is subtle, and only a matter of coding style. This cannot cause any problems, but it can perhaps cause implicit typecast warnings.

I interpret the rule as "everything that isn't Boolean should be explicitly tested". Consider this:


If y is a pointer, this is surely poor coding style, since ! is a pure Boolean operator.

Re: Doubt on rule 13.2

Posted: Mon Mar 02, 2009 11:25 am
by misra-c
The interpretation, as expounded by lundin, is correct. The rule is intended to apply to all tests against 0 and this inclues testing pointers against NULL.

The rationale for this rule is to make a clear distinction between types that are being interpreted as Booleans (flags) and another other types.