(Why) is using an uninitialized variable undefined behavior?

后端 未结 7 2353
暗喜
暗喜 2020-11-21 05:01

If I have:

unsigned int x;
x -= x;

it\'s clear that x should be zero after this expression, but everywhere I look, th

7条回答
  •  臣服心动
    2020-11-21 05:27

    For any variable of any type, which is not initialized or for other reasons holds an indeterminate value, the following applies for code reading that value:

    • In case the variable has automatic storage duration and does not have its address taken, the code always invokes undefined behavior [1].
    • Otherwise, in case the system supports trap representations for the given variable type, the code always invokes undefined behavior [2].
    • Otherwise if there are no trap representations, the variable takes an unspecified value. There is no guarantee that this unspecified value is consistent each time the variable is read. However, it is guaranteed not to be a trap representation and it is therefore guaranteed not to invoke undefined behavior [3].

      The value can then be safely used without causing a program crash, although such code is not portable to systems with trap representations.


    [1]: C11 6.3.2.1:

    If the lvalue designates an object of automatic storage duration that could have been declared with the register storage class (never had its address taken), and that object is uninitialized (not declared with an initializer and no assignment to it has been performed prior to use), the behavior is undefined.

    [2]: C11 6.2.6.1:

    Certain object representations need not represent a value of the object type. If the stored value of an object has such a representation and is read by an lvalue expression that does not have character type, the behavior is undefined. If such a representation is produced by a side effect that modifies all or any part of the object by an lvalue expression that does not have character type, the behavior is undefined.50) Such a representation is called a trap representation.

    [3] C11:

    3.19.2
    indeterminate value
    either an unspecified value or a trap representation

    3.19.3
    unspecified value
    valid value of the relevant type where this International Standard imposes no requirements on which value is chosen in any instance
    NOTE An unspecified value cannot be a trap representation.

    3.19.4
    trap representation
    an object representation that need not represent a value of the object type

提交回复
热议问题