3.5 Types

3.5.1 Do not make any assumptions about the internal representation of a value or object

Avoid C++ constructs and practices that are likely to make your code non-portable:

  • A union provides a way to alter the type ascribed to a value without changing its representation. This reduces type safety and is usually unnecessary. In general it is possible to create a safe abstraction using polymorphic types.
  • Integer types other than signed / unsigned char have implementation defined size. Do not use integer types directly, instead use size specific typedefs, defined in a common header file, which can then be easily adjusted to match a particular platform.
  • Do not mix bitwise and arithmetic operations on the same variable, as this is likely to be non portable between big and little endian architectures.
  • Do not assume the layout of objects in memory, e.g. by comparing pointers to different objects with the relational operators, using the offsetof macro, or performing pointer arithmetic within an object with unspecified or implementation defined layout.
#include <cstdint>
               
union U             // @@- Non-Compliant -@@
{
float f;
int32_t i;        // @@- Non-Compliant -@@
};
               
uint32_t foo (uint32_t u)
{
--u;
return u & 0xFFU; // @@- Non-Compliant: mixing arithmetic and bitwise operations -@@
}
               
bool cmp (int32_t * lhs, int32_t * rhs)
{
return lhs < rhs; // @@- Non-Compliant -@@
}

References

  • HIC++ v3.3 - 13.6
  • HIC++ v3.3 - 15.1
  • JSF AV C++ Rev C - 210
  • JSF AV C++ Rev C - 210.1
  • JSF AV C++ Rev C - 147
  • JSF AV C++ Rev C - 215
  • MISRA C++:2008 - 3-9-3
  • MISRA C++:2008 - 5-0-15

Click here for references