0

i'm a student of IT and i have some general academic knownledge of C. Recently i started to study C++ but i'm stuck to this strange thing i that found now about assignments.

1^ program:

int main() {
int x;

cout << x;
return 0;
}

x is printed in stdout as 0.

2^ program:

int main() {    
    int x, y=2;

cout << x << endl << y;
return 0;
}

x is printed in stdout as 1.

Anyone can explain me, please?

Thanks, Gabriele.

Spinkoo
  • 2,080
  • 1
  • 7
  • 23
  • 1
    "*i have some general academic knownledge of C*" - are you aware of so-called *undefined behaviour*? It's the same in `C++`. What would happen if you did `int x; printf("%d", x);` in `C`? – Fureeish Feb 10 '19 at 20:42
  • C requires you to initialize any variable before you use it for deterministic behavior. – Jonathan Wood Feb 10 '19 at 20:43
  • 1
    Please take a look at the following link to see how you can place your code nicely in a question https://stackoverflow.com/editing-help – Gazihan Alankus Feb 10 '19 at 20:45
  • @Fureeish no, i'm not. I just asked to have some comparison. Anyway i guess it will printed the random value assigned at runtime. I run this programs several times before asking here, and i got always the same result. – blackfromabove Feb 11 '19 at 14:36

1 Answers1

0

Uninitialized local variables do not have a determined value. This usually depends on what's there in memory. Never use an uninitialized local variable.

Gazihan Alankus
  • 11,256
  • 7
  • 46
  • 57
  • 1
    That's not quite a *random value*. It's undefined behaviour. It's not even safe to assume that accessing a single, uninitialised variable twice will yield the same value. – Fureeish Feb 10 '19 at 20:45
  • @Gazi Alankus Yes i always followed this rule while using C. I just doing some exercises and i found this. – blackfromabove Feb 11 '19 at 14:36
  • If you got that code from somewhere, I think we can conclude that it's not a trustworthy source. – Gazihan Alankus Feb 12 '19 at 10:07