Rule 4-5-1 prohibits 'b1 |= b2;' ?

Moderators: david ward, misra cpp

Post Reply
grunwald
Posts: 14
Joined: Wed May 14, 2014 1:02 pm
Company: Axivion GmbH

Rule 4-5-1 prohibits 'b1 |= b2;' ?

Post by grunwald » Wed Sep 28, 2016 3:00 pm

Neither `|` nor `|=` is listed as allowed operator.
Does this mean the following code a violation of Rule 4-5-1?

Code: Select all

bool b1 = false;

void f(int x)
{
    b1 |= (x == 0);
}

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

Re: Rule 4-5-1 prohibits 'b1 |= b2;' ?

Post by dg1980 » Thu Sep 29, 2016 1:46 pm

grunwald wrote:Neither `|` nor `|=` is listed as allowed operator.
Does this mean the following code a violation of Rule 4-5-1?

Code: Select all

bool b1 = false;

void f(int x)
{
    b1 |= (x == 0);
}
x |= y is just short for x = x | y and bitwise operators are forbidden by the rationale in this rule.

Code: Select all

FlexeLint for C/C++ (Unix) Vers. 9.00L, Copyright Gimpel Software 1985-2014
--- Module: diy.cpp (C++)
     1  //lint -indirect(au-misra-cpp-alt.lnt) -e514 -e1786 -e9141 -e970 -e952
     2  bool b1 = false;
     3  
     4  void f(int x)
     5  {
                          _
     6      b1 |= (x == 0);
diy.cpp  6  Note 9111:  boolean expression used with non-permitted operator ''|'' [MISRA C++ Rule 4-5-1]
diy.cpp  6  Note 9111:  boolean expression used with non-permitted operator ''|'' [MISRA C++ Rule 4-5-1]

mishak
Posts: 10
Joined: Thu Jun 21, 2007 3:58 pm

Re: Rule 4-5-1 prohibits 'b1 |= b2;' ?

Post by mishak » Thu Sep 29, 2016 2:46 pm

Remember that any non-zero value will be considered as 'true' within a logical context, which can lead to surprises:

Code: Select all

a = 0x01u;   // This is logically 'true'
b = 0x10u;   // This is logically 'true'

if ( a &  b )   // Result of bit-wise 'and' is 'false'
if ( a && b )   // Result of logical 'and' is true
Rule 4-5-1 helps to enforce a consistent use of boolean types, helping to allowing defects to be detected.
Last edited by misra cpp on Tue Oct 11, 2016 1:58 pm, edited 1 time in total.

misra cpp
Posts: 150
Joined: Mon Jun 02, 2008 1:55 pm
Company: MISRA

Re: Rule 4-5-1 prohibits 'b1 |= b2;' ?

Post by misra cpp » Fri Oct 28, 2016 12:40 pm

Yes, b1 |= b2 is prohibited

As pointed out by dg1980, |= is a bitwise operator and the rationale of the rule prohibits the use of bitwise operators
Posted by and on behalf of
the MISRA C++ Working Group

Post Reply

Return to “6.4 Standard conversions (C++)”