2

This is pretty simple, yet I cannot explain it. I declare 4 variables, and print it out in C++:

#include <iostream>
using namespace std;

int main(){
  int a, b, c, d;

  cout << "a = " << a << endl;
  cout << "b = " << b << endl;
  cout << "c = " << c << endl;
  cout << "d = " << d << endl;

  return 0;
}

And the result is:

a = 0
b = 1
c = 0
d = 0

I thought if I don't initialize value for a variable, the program will take some random value from the memory for it. Or at least it's all equal to zero. I don't know where the difference of those values come from.

This is not because of a specific variable b, if I switch those "cout <<" lines, the second line always give the value = 1.

Can anyone explain this for me, please. Thank you so much.

Notinlist
  • 16,144
  • 10
  • 57
  • 99
Huyen
  • 443
  • 4
  • 17

1 Answers1

3

Reading an uninitialized variable is Undefined Behaviour in C++.

The compiler is free to generate whatever code it likes for your program, since you broke the rules of the language.

Your program may crash, do exactly what you expect, run forever or do any other thing you can imagine.

Now reasonable implementations of compilers won't use UB as an excuse to format your harddrive (but they could), but UB still means that your program has no meaning according to the standard and that you can and will get arbitrary results across compilers and operating systems. Don't expect that the result you see now, with your current compiler, on your current OS, will be the same in a different situation with a different compiler or on a different OS, when UB is involved.

In a nutshell; it's your responsibility to not invoke UB. The compiler is not required to warn you. And if you want a program with deterministic behaviour, you need to not invoke UB.

Jesper Juhl
  • 30,449
  • 3
  • 47
  • 70
  • I get that one should not read an uninitialized variable. My question is, if I let this line 'cout << "c = " << c << endl;' instead of print b, I will have c = 1 instead. This is about the order thingy that I don't get yet. – Huyen Aug 08 '17 at 19:21
  • @Nguyễn Ngọc Huyền you can't reason about your program when it contains UB. Any result/effect you see is arbitrary and *not* deterministic. Stop trying to reason about what you currently observe and instead *fix* the UB - *then* you can start to try and reason about your programs behaviour. And btw `cout << "c = " << c` *is* reading an uninitialized variable --> UB. – Jesper Juhl Aug 08 '17 at 19:25
  • @Nguyễn Ngọc Huyền - What's "harsh"? I'm just trying to state *facts* - clear and simple. – Jesper Juhl Aug 08 '17 at 19:34