Reputation: 101
For some reason, the value of final_sum
is 16 but I didn't initialize a value for that variable, why's that? Isn't supposed to start with 0
?
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
int main()
{
int n, sum, final_sum;
cout<<"ff: "<<final_sum<<endl;
cout<<"Input the value for n: ";
cin>>n;
for(int i=1; i<=n; i++){
sum += i;
final_sum += sum;
cout<<"sum: "<<sum<<endl;
cout<<"final sum: "<<final_sum<<endl<<endl;
}
return 0;
}
Upvotes: 0
Views: 295
Reputation: 1
Declaring the variable globally does the job
int final_sum;
int main() {
your code ...
}
is the same as
int final_sum = 0;
int main() {
your code here ...
}
However, you probably don't want to use global variables and it is always recommended to initialize variables with some value.
Upvotes: 0
Reputation: 1662
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?
Upvotes: 3
Reputation: 2870
Isn't supposed to start with 0
No, its initial value is undefined. See https://en.cppreference.com/w/cpp/language/default_initialization
the objects with automatic storage duration (and their subobjects) are initialized to indeterminate values.
If you do
int final_sum{};
Or
int final_sum = 0;
You will have a 0
in your variable.
I suggest you to use -Wuninitialized
(or better -Wall
). The compiler will raise a warning if you forgot and initialization
Upvotes: 5