Moderators: david ward, misra cpp
- Posts: 5
- Joined: Tue Mar 13, 2018 7:58 am
- Company: Denso Create
Why are the following MISRA Example compliant?
Is not a sub-expression?
Code: Select all
if ( int16_t i = foo ( ) ) // Compliant
It looks like the following, but the following are non-compliant.
What are the differences?
Code: Select all
if ( x = y ) // Non-compliant
ã€€foo ( );
- Posts: 109
- Joined: Wed Apr 27, 2016 2:33 pm
- Company: Elektrobit Automotive GmbH
IMHO, both are technically sub-expressions.
It's either a mistake that the second one is compliant or the intent of MISRA was to add an explicit exception for declaration+initialization of block scope variables like i (x is not, so you have the side effect of changing its value + confusing it with ==).
Anyway, an official clarification would be nice.
- Posts: 151
- Joined: Mon Jun 02, 2008 1:55 pm
- Company: MISRA
Firstly, we agree with nishiyamaâ€™s interpretation of 6-2-1, the first example is compliant and the second isnâ€™t. The technical reason for why the first is compliant is that it doesnâ€™t contain an assignment (as defined by the C++ standard). When an object is declared, what appears to be an assignment is an initialisation. The C++ standard defines different behaviours for assignment and initialisation (e.g. you cannot assign to a const object, but you can â€“ indeed must â€“ initialise it), so MISRA C++ makes the same distinction.
The more practical reason is that there is no reason to ban if ( int16_t i = foo ( ) ) as there is no possibility of unexpected or undefined behaviour and it would be difficult to ban without also banning for ( int16_t i = 0; â€¦ which is such a common coding idiom that it has to be allowed.
Posted by and on behalf of
the MISRA C++ Working Group