Rule 6-2-1 Assignment operators shall not be used in subexpressions - Printable Version +- MISRA Discussion Forums (https://forum.misra.org.uk) +-- Forum: MISRA C++ (https://forum.misra.org.uk/forumdisplay.php?fid=18) +--- Forum: MISRA C++:2008 rules (https://forum.misra.org.uk/forumdisplay.php?fid=19) +---- Forum: 6.6 Statements (C++) (https://forum.misra.org.uk/forumdisplay.php?fid=135) +---- Thread: Rule 6-2-1 Assignment operators shall not be used in subexpressions (/showthread.php?tid=1428) |
Rule 6-2-1 Assignment operators shall not be used in subexpressions - nishiyama - 30-05-2018 Hello. Why are the following MISRA Example compliant? Is not a sub-expression? Code: if ( int16_t i = foo ( ) ) // Compliant It looks like the following, but the following are non-compliant. What are the differences? Code: if ( x = y ) // Non-compliant Re: Rule 6-2-1 Assignment operators shall not be used in subexpressions - dg1980 - 30-05-2018 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. Re: Rule 6-2-1 Assignment operators shall not be used in subexpressions - misra cpp - 17-07-2018 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. |