int a; …; (a == a) fails?

后端 未结 9 1006
执笔经年
执笔经年 2020-12-31 19:05

if we set float and double type to NaN then they are not equal to anything including themselves.
can such a thing happens for

9条回答
  •  不知归路
    2020-12-31 19:16

    Since C++20, the answer (for initialized variables) is no.

    As proposal P0907 explains, signed integers previously allowed various value representations, including "the existence of an extraordinary value which traps, extra padding bits, [and] integral negative zero." (Hence Potatoswatter's answer that, in theory, NaN values for ints were possible.) In practice, though, every machine running C++ uses a "normal" two's complement representation for signed integers.

    Supporting that proposal, the C++ standards committee decided to standardize two's complement and to disallow extraordinary values. Now, the value representation of signed integers is fixed, and while integers can also have padding bits, the standard stops them from doing anything unusual: (basic.fundamental)

    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 cannot cause traps. In contrast, see ISO C 6.2.6.2. — end note]

    Therefore, ints have no extraordinary values that could produce NaN-like behavior.

提交回复
热议问题