C++ standard
If a C++14
implementation includes padding bits in the underlying bytes of an unsigned int
, does the standard specify if bitwise operations must not be performed on padding bits ?
Additionally, does the C++14 standard specify if equality and relational
operators must ignore the padding bits ?
Guidelines
If there is a lack of specification on that matter, is there some kind of consensus on the expected behavior of those operators on padding bits?
I found conflicting answers on Stack Overflow. Lightness Races in Orbit and ecatmur say that bitwise operators are unsuitable for arithmetic because they are applied on all bits (including padding bits), while Christoph and Bartek Banachewicz say that the bitwise operators work on the logical value of integers and ignore padding.
References
Related answers: on the existence of padding bits (1, 2, 3), on the absence of clear C++ specification (4).
Definition of padding bits in C++14 - § 3.9.1 - Fundamental types:
For narrow character types, all bits of the object representation participate in the value representation. For unsigned narrow character types, all possible bit patterns of the value representation represent numbers. These requirements do not hold for other types.
Definition of object representation and value representation in C++14 - § 3.9 - Types:
The object representation of an object of type
T
is the sequence of Nunsigned char
objects taken up by the object of typeT
, where N equalssizeof(T)
. The value representation of an object is the set of bits that hold the value of typeT
. For trivially copyable types, the value representation is a set of bits in the object representation that determines a value, which is one discrete element of an implementation-defined set of values.44Footnote 44) The intent is that the memory model of C++ is compatible with that of ISO/IEC 9899 Programming Language C.
Definition of bitwise AND in C++14 - § 5.11 - Bitwise AND operator:
The usual arithmetic conversions are performed; the result is the bitwise AND function of the operands. The operator applies only to integral or unscoped enumeration operands.
Definition of addition in C++14 - § 5.7 - Additive operators:
The usual arithmetic conversions are performed for operands of arithmetic or enumeration type. For addition, [...] both operands shall have arithmetic or unscoped enumeration type [...]. The result of the binary
+
operator is the sum of the operands.