0

I was taught that when I declare a type "int x" the default value of it will be 0, but when I try to print it or make "x+=10" it shows some random numbers(maybe memory point). But everything works fine when I type "int x=0;" and "x+=10" the answer is 10. So what is a difference between int x; and int x=0; ?

Eldiiar
  • 9
  • 1
  • 3
    Who taught you that there is a default value for `int` in C++? – Scott Hunter Jun 16 '20 at 15:32
  • https://stackoverflow.com/questions/6032638/default-variable-value – Nick Juelich Jun 16 '20 at 15:32
  • 1
    *"I was taught that when I declare a type "int x" the default value of it will be 0"* - whoever taught you this was wrong (for primitive types). – 0x5453 Jun 16 '20 at 15:33
  • 1
    The sentence should be: _"when I declare a non-local variable "int x" the default value of it will be 0"_ It doesn't work with local variables. – Thomas Sablik Jun 16 '20 at 15:35
  • If it is a global variable it will be 0. A local variable will have a garbage value. That garbage value may even be 0 the first time you run your function tricking you into believing that your compiler is setting it to 0. The reason for this is your OS may give memory pages to your program that is filled with 0s to avoid leaking sensitive information from the last program that used the same physical memory. – drescherjm Jun 16 '20 at 19:30

1 Answers1

0

The default value is not guaranteed to be zero when you declare it. If residual information exists on the area where the program was loaded, you may experience surprises. When you also initialize its value, then you have the guarantee that the variable has the value you expect.

ecazamir
  • 61
  • 3