Reputation: 845
Consider the following code:
#include "stdafx.h"
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
int count123;
for (int c = 0; c < 10; c++)
{
count123 += c;
}
return 0;
}
Upon compilation I get the warning: warning C4700: uninitialized local variable 'count123' used
I know the reason is declaring count123 but not initializing it.
But if I declare count123 as a global variable as in the code below, the warning disappears.
#include "stdafx.h"
using namespace std;
int count123;
int _tmain(int argc, _TCHAR* argv[])
{
for (int c = 0; c < 10; c++)
{
count123 += c;
}
return 0;
}
As far as I know declaring count123 as a global variable would change its scope but how does that remove the warning? Please guide.
Upvotes: 1
Views: 137
Reputation: 1665
Global variables are initialized by zero always, think of a global pointer, initialized with some random value, and you used it in your code mistakenly. Global initialization makes it NULL, so you can check it and use accordingly.
— if it has pointer type, it is initialized to a null pointer;
— if it has arithmetic type, it is initialized to (positive or unsigned) zero;
Upvotes: 2
Reputation: 5619
The global variables are initialized with zero by default, hence you got no warnings.
You can easily get the draft of C++ standards then read the section 8.5 Initializers:
10 [ Note: Every object of static storage duration is zero-initialized at program startup before any other initialization takes place. In some cases, additional initialization is done later. —end note ]
Upvotes: 1
Reputation: 1666
Global variables are static storage variables and these are by default zero-initialized. For more information, please see the answer here.
Upvotes: 2
Reputation: 73376
The global variables are zero initialized (by the way, the same applies to statics variables). THis is why you don't get this message.
Here the standard quote:
8.5/10: Every object of static storage duration is zero-initialized at program startup before any other initialization takes place. In some cases, additional initialization is done later.
Upvotes: 5