This is mainly a followup to that other question. OP wanted to guess whether a variable contained an int or not, and my first thought was that in C (as in C++) an int variable could only contain an int value. And Eric Postpischil reminded me that trap representations were allowed per standard for the int type...
Of course, I know that most modern system only use 2-complement representations of integers and no padding bits, meaning that no trap representation can be observed. Nevertheless both standards seem to still allow for 3 representations of signed types: sign and magnitude, one's complement and two's complement. And at least C18 draft (n2310 6.2.6 Representations of types) explicitely allows padding bits for integer types other that char.
So in the context of possible padding bits, or non two's complement signed representation, int
variables could contain trap values for conformant implementations. Is there a reliable way to make sure that an int variable contains a valid value?
In C++'s current working draft (for C++20), an integer cannot have a trap representation. An integer is mandated as two's complement: ([basic.fundamental]/3)
An unsigned integer type has the same object representation, value representation, and alignment requirements ([basic.align]) as the corresponding signed integer type. For each value x of a signed integer type, the value of the corresponding unsigned integer type congruent to x modulo 2N has the same value of corresponding bits in its value representation. 41 [ Example: The value −1 of a signed integer type has the same representation as the largest value of the corresponding unsigned type. — end example ]
Where the note 41 says
This is also known as two's complement representation.
This was changed in p0907.
Additionally, padding bits in integers cannot cause traps: ([basic.fundamental/4])
Each set of values for any padding bits ([basic.types]) in the object representation are alternative representations of the value specified by the value representation. [ Note: Padding bits have unspecified value, but do not cause traps. See also ISO C 6.2.6.2. — end note ]