rspec/rules/S853/cfamily/rule.adoc
Fred Tingaud 16f6c0aecf
Inline adoc when include has no additional value (#1940)
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.
2023-05-25 14:18:12 +02:00

58 lines
1.8 KiB
Plaintext

== Why is this an issue?
When ``++~++`` and ``++<<++`` are applied to small integer types (``++unsigned char++`` or ``++unsigned short++``), the operations are preceded by integral promotion, and the result may contain high-order bits which have not been anticipated.
=== Noncompliant code example
[source,cpp]
----
unsigned char port = 0x5aU;
unsigned char result_8;
unsigned short result_16;
unsigned short mode;
result_8 = (~port) >> 4; // Noncompliant; '~port' is 0xFFA5 on a 16-bit machine but 0xFFFFFFA5 on a 32-bit machine. Result is 0xFA for both, but 0x0A may have been expected.
result_16 = ((port << 4) & mode) >> 6; // Noncompliant; result_16 value depends on the implemented size of an int.
----
=== Compliant solution
[source,cpp]
----
result_8 = ((unsigned char)(~port)) >> 4; // Compliant
result_16 = ((unsigned short)((unsigned short) port << 4) & mode) >> 6; // Compliant
----
== Resources
* MISRA C 2004, 10.5 - If the bitwise operators ~ and << are applied to an operand of _underlying type_ unsigned char or unsigned short, the result shall be immediately cast to the _underlying type_ of the operand.
* MISRA {cpp} 2008, 5-0-10 - If the bitwise operators ~ and << are applied to an operand with an _underlying type_ of unsigned char or unsigned short, the result shall be immediately cast to the _underlying type_ of the operand.
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
=== Message
Add an explicit cast to the result of the 'x' operator.
'''
== Comments And Links
(visible only on this page)
=== relates to: S5451
=== on 21 Oct 2014, 18:34:06 Ann Campbell wrote:
\[~samuel.mercier] please
* move the code commentary into the code in the form of comments if needed
endif::env-github,rspecator-view[]