0

Reading uninitialized variables leads to undefined behavior, e.g.

#include <iostream>

int main()
{
    int a;
    std::cout << a << std::endl; // undefined behavior
}

Can someone give a formal explanation of this fact?

M.M
  • 138,810
  • 21
  • 208
  • 365
St.Antario
  • 26,175
  • 41
  • 130
  • 318
  • You want someone to _define_ undefined behaviour? –  May 30 '15 at 05:55
  • @HoboSapiens No, I want to understand why reading the uninitialized variables is UB. – St.Antario May 30 '15 at 05:56
  • 1
    Because the C++ spec says so ... I imagine. Did you try reading it before you asked? Or are you just asking someone else to read the spec for you? (And in the latter case ... do you need someone else to read the SO Answer for you? :-) ) – Stephen C May 30 '15 at 05:57
  • @StephenC Yes. I've read the chapter 3 about initialization but didn't find. – St.Antario May 30 '15 at 05:59
  • @St.Antario A better example would be using an uninitialized `double` instead of `int`. The uninitialized double may be a NAN of infinity, thus yielding undefined behavior if you use it. – PaulMcKenzie May 30 '15 at 06:05
  • @PaulMcKenzie - I don't see the distinction. If the `int` is uninitialized, then you don't know what would be printed ... and that is the "undefined" aspect of the behaviour. – Stephen C May 30 '15 at 06:16
  • have linked as duplicate - the other thread also has language-lawyer quality answers, and newer standard references, so this will avoid repetition of answers – M.M Sep 12 '16 at 05:50

1 Answers1

5

Here is the relevant section, I think:

4.1 Lvalue-to-rvalue conversion

1 - A glvalue of a non-function, non-array type T can be converted to a prvalue. If T is an incomplete type, a program that necessitates this conversion is ill-formed. If the object to which the glvalue refers is not an object of type T and is not an object of a type derived from T, or if the object is uninitialized, a program that necessitates this conversion has undefined behavior.

A variable is an lvalue, and I think an "lvalue to rvalue conversion" is the process of taking a variable's value.

(Note - I'm not familiar with the C++ standards, so I may have not found the part that applies to this example. All I did was search the PDF for "uninitialized", and look for the hit that looks most relevant.)

Community
  • 1
  • 1
Stephen C
  • 698,415
  • 94
  • 811
  • 1,216