How to check whether an int variable contains a legal (not trap representation) value?

这一生的挚爱 提交于 2020-01-12 23:31:24

问题


Context:

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.

Question

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?


回答1:


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 ]



来源:https://stackoverflow.com/questions/59623552/how-to-check-whether-an-int-variable-contains-a-legal-not-trap-representation

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!