Reputation: 1533
I just made this program which asks to enter number between 5 and 10 and then it counts the sum of the numbers which are entered. Here is the code:
#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
int a,i,c;
cout << "Enter the number between 5 and 10" << endl;
cin >> a;
if (a < 5 || a > 10)
{
cout << "Wrong number" << endl;
system("PAUSE");
return 0;
}
for(i=1; i<=a; i++)
{
c=c+i;
}
cout << "The sum of the first " << a << " numbers are " << c << endl;
system("PAUSE");
return 0;
}
If I enter 5
, it should display
The sum of the first 5 numbers are 15
but it displays
The sum of the first 5 numbers are 2293687
When I set c
to 0
, it works correctly.
So what is the difference?
Upvotes: 6
Views: 28414
Reputation: 56479
Because C++ doesn't automatically set it zero for you. So, you should initialize it yourself:
int c = 0;
An uninitialized variable has a random number such as 2293687
, -21
, 99999
, ... (If it doesn't invoke undefined behavior when reading it)
Also, static
variables will be set to their default value. In this case 0
.
Upvotes: 21
Reputation: 101456
Because when you do:
int a,i,c;
thus instantiating and initializing c
, you haven't said what you want it initialized to. The rules here are somewhat complex, but what it boils down to is two things:
Upvotes: 0
Reputation: 36438
Non-static variables are, by definition, uninitialized - their initial values are undefined.
On another compiler, you might get the right answer, another wrong answer, or a different answer each time.
C/C++ don't do extra work (initialization to zero involves at least an instruction or two) that you didn't ask them to do.
Upvotes: 5
Reputation: 106012
The sum of the first 5 numbers are 2293687
This is because without initializing c
you are getting value previous stored at that location (garbage value). This will make yor program's behavior undefined. You must have to initialize c
before using it in your program.
int c= 0;
Upvotes: 0
Reputation: 227418
If you don't set c
to 0
, it can take any value (technically, an indeterminate value). If you then do this
c = c + i;
then you are adding the value of i
to something that could be anything. Technically, this is undefined behaviour. What happens in practice is that you cannot rely on the result of that calculation.
In C++, non-static or global built-in types have no initialization performed when "default initialized". In order to zero-initialize an int
, you need to be explicit:
int i = 0;
or you can use value initialization:
int i{};
int j = int();
Upvotes: 8