If you don't initialize a variable before reading/using it, its undefined behavior
. Its value can then be anything, it's unpredictable and always a bad idea. Use
int final_sum = 0;
to initialize it.
From documentation:
The value in an uninitialized variable can be anything – it is
unpredictable, and may be different every time the program is run.
Reading the value of an uninitialized variable is undefined behaviour
– which is always a bad idea. It has to be initialized with a value
before you can use it.
and
The only place where they are useful is when you are about to read the
variable in from some input stream.
Edit : Some may ask "Why my variable still print 0
even though I haven't initialize it?"
From this post :
That is because variables with automatic storage duration are not
automatically initialized to zero in C++. In C++, you don't pay for
what you don't need, and automatically initializing a variable takes
time (setting to zero a memory location ultimately reduces to machine
intruction(s) which are then translated to electrical signals that
control the physical bits).
So when you do :
int final_sum;
The final_sum
is just being reserved a memory location, and anything currently inside that location will be printed out by cout
. It just happened that there's a big 0
in that spot.
More info : (Why) is using an uninitialized variable undefined behavior?