cinitializationlanguage-lawyerundefined-behaviorunspecified-behavior

Is reading values of unitialized object yields Undefined Behavior


The simplest example:

int a;
printf("%d\n", a); //Is this Undefined or Unspecified behavior?

N2346/6.3.2.1p2:

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.

But N2346/6.7.9p10:

If an object that has automatic storage duration is not initialized explicitly, its value is indeterminate.

So we can conclude that the object is initialized to some indeterminate value. The indeterminate value is well defined at

N2346/3.19.2p1:

indeterminate value

either an unspecified value or a trap representation

Since the representation of int is never a trap and applying N2346/3.4.4p1

unspecified behavior

behavior, that results from the use of an unspecified value, or other behavior upon which this document provides two

we have that the program has unspecified behavior.

Where does this reasoning fail?


Solution

  • Where does this reasoning fail?

    One failure is here

    Since the representation of int is never a trap

    int can have trap representations.

    The only type that can't have trap representations is unsigned char

    But there is also this part in the standard describing undefined behavior (from draft n1570):

    J.2 Undefined behavior

    ...

    An lvalue designating an object of automatic storage duration that could have been declared with the register storage class is used in a context that requires the value of the designated object, but the object is uninitialized. (6.3.2.1).