Rule 14.4 and the explanation is not enough to understand why

Moderators: misra-c, david ward

Post Reply
xiangke
Posts: 9
Joined: Tue Apr 11, 2017 7:34 am
Company: valeo

Rule 14.4 and the explanation is not enough to understand why

Post by xiangke » Tue Jun 06, 2017 10:54 am

MISRA C 2012 guideline says:
Strong typing requires the controlling expression of an if statement or iteration-statement to have
essentially Boolean type.

For example:
typedef unsigned short tudtKalEvents;
#define udtSTOP_EVENT (tudtKalEvents)0x0001;

Code: Select all

  if(udtEvents & (tudtKalEvents) udtSTOP_EVENT)
  {
        vidStop();
  }
I think the code is ok, I use the & statement as the conditional expression. As we know, the value is not equal to zero, the condition shall be judged to be true,
why We must use the boolean type?

dg1980
Posts: 109
Joined: Wed Apr 27, 2016 2:33 pm
Company: Elektrobit Automotive GmbH

Re: Rule 14.4 and the explanation is not enough to understand why

Post by dg1980 » Thu Jun 08, 2017 8:25 am

Just to be clear, you don't need to use the boolean type, but you need to form a boolean expression, e.g.

Code: Select all

if ((udtEvents & (tudtKalEvents)udtSTOP_EVENT) != 0u)
{
  vidStop();
}
It´s all about avoiding implicit conversion as much as possible.

misra-c
Posts: 566
Joined: Thu Jan 05, 2006 1:11 pm

Re: Rule 14.4 and the explanation is not enough to understand why

Post by misra-c » Wed Jun 14, 2017 9:23 am

MISRA-C introduces a strong typing model to help users avoid unexpected issues which occur in the C typing model.
The rule prevents the accidental use of integer expression when a boolean expression was intended.

To be compliant with MISRA rule 14.4 you should write your test as a boolean expression:

Code: Select all

if((udtEvents & udtSTOP_EVENT) != 0U  )
---
Posted by and on behalf of
the MISRA C Working Group

Post Reply

Return to “8.14 Control statement expressions”