Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Doubt on rule 13.2
#1
One of the examples given for rule 13.2 is:

Code:
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?
<t></t>
Reply
#2
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.
<t></t>
Reply
#3
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:
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:
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?
Thanks,

Roberto
<t></t>
Reply
#4
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)

If y is a pointer, this is surely poor coding style, since ! is a pure Boolean operator.
<t></t>
Reply
#5
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.
Posted by and on behalf of the MISRA C Working Group
Reply


Forum Jump:


Users browsing this thread: 2 Guest(s)