MISRA Discussion Forums
A4-5-1 with ternary conditional operator - Printable Version

+- MISRA Discussion Forums (https://forum.misra.org.uk)
+-- Forum: MISRA C++ (https://forum.misra.org.uk/forumdisplay.php?fid=18)
+--- Forum: AUTOSAR C++:2014 rules (https://forum.misra.org.uk/forumdisplay.php?fid=185)
+--- Thread: A4-5-1 with ternary conditional operator (/showthread.php?tid=1612)



A4-5-1 with ternary conditional operator - Tobias Loose - 08-04-2022

Hi!

The rule states:


Quote:Expressions with type enum or enum class shall not be used as operands to built-in and overloaded operators other than the subscript operator [ ], the assignment operator =, the equality operators == and ! =, the unary & operator, and the relational operators <, <=, >, >=.


I can understand the rule insofar as to avoid confusion that is caused by using the underlying type arithmetically. However, this also excludes the ternary conditional operator, and thus, this IMHO perfectly fine code:

Code:
void foo()
{
   enum class Thing { One, TheOther };

   bool which_one = g();

   const Thing selected_thing = which_one ? Thing::One : Thing::TheOther; // Non-compliant with A4-5-1
}

Please note that turning this into an "if" will add another statement and preclude "selected_thing" from being const. Depending on the C++ version, this also precludes the surrounding function from being constexpr (because of the extra statement). In my opinion, the demonstrated usage should be allowed in general.

Is it an oversight to disallow enum values in these cases, or is there a specific reason? If there is a reason, I would urge you to overthink your stance on this w.r.t. the upcoming MISRA C++.

Edit: Also, this code violates A5-16-1, because it uses the ternary conditional operator as a subexpression of the assignment expression. I guess this is an oversight in A5-16-1, which should have an exception for assignment expressions.

Thanks!


RE: A4-5-1 with ternary conditional operator - misra cpp - 13-05-2022

You are right, your example does violate A5-4-1, and this is probably an oversight in the drafting.

As far as A5-16-1 is concerned, the last line of foo() is virtually the same as a compliant example, so Autosar was probably intending to include the ternary operator.

This is being reviewed for the next version of the rules.