
Inline adoc files when they are included exactly once. Also fix language tags because this inlining gives us better information on what language the code is written in.
82 lines
1.6 KiB
Plaintext
82 lines
1.6 KiB
Plaintext
== Why is this an issue?
|
|
|
|
It is unspecified behaviour if the evaluation of an expression with ``++enum++`` underlying type yields a value which does not correspond to one of the enumerators of the enumeration.
|
|
|
|
|
|
Additionally, other rules in this standard assume that objects of ``++enum++`` type only contain values corresponding to the enumerators. This rule ensures the validity of these assumptions.
|
|
|
|
|
|
One way of ensuring compliance when converting to an enumeration is to use a switch statement.
|
|
|
|
|
|
=== Noncompliant code example
|
|
|
|
[source,cpp]
|
|
----
|
|
enum Numbers {
|
|
ONE, TWO
|
|
};
|
|
|
|
int function() {
|
|
enum Numbers c = (enum Numbers)(TWO + TWO); // Noncompliant, operation might yield an invalid value.
|
|
}
|
|
----
|
|
|
|
|
|
=== Compliant solution
|
|
|
|
[source,cpp]
|
|
----
|
|
enum Numbers {
|
|
ONE, TWO
|
|
};
|
|
|
|
enum Numbers convert ( int16_t v )
|
|
{
|
|
switch ( v )
|
|
{
|
|
case 0:
|
|
return ONE;
|
|
case 1:
|
|
return TWO;
|
|
default:
|
|
throw ENUM_ERROR;
|
|
}
|
|
}
|
|
|
|
int function() {
|
|
enum Numbers c = convert(ONE + TWO); // Compliant
|
|
}
|
|
----
|
|
|
|
|
|
== Resources
|
|
|
|
* MISRA {cpp}:2008, 7-2-1
|
|
|
|
|
|
ifdef::env-github,rspecator-view[]
|
|
|
|
'''
|
|
== Implementation Specification
|
|
(visible only on this page)
|
|
|
|
=== Message
|
|
|
|
Refactor this conversion from "xxx" to "yyy".
|
|
|
|
|
|
'''
|
|
== Comments And Links
|
|
(visible only on this page)
|
|
|
|
=== on 23 Oct 2014, 16:17:07 Ann Campbell wrote:
|
|
\[~samuel.mercier] FYI, I've updated the code examples.
|
|
|
|
Noncompliant, I changed to actually yield an invalid valid. Since enums start at 0, ONE + TWO yields TWO, which is clearly valid. But TWO + TWO does not.
|
|
|
|
|
|
Also modified compliant to fix a typo.
|
|
|
|
endif::env-github,rspecator-view[]
|