1

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.

Community
  • 1
  • 1
Ruchir
  • 845
  • 2
  • 10
  • 24

4 Answers4

5

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.

Christophe
  • 68,716
  • 7
  • 72
  • 138
  • Thanks for the answer @Christophe. Please clarify what do you mean by "as well as the statics" – Ruchir Aug 03 '15 at 09:48
  • 1
    He means Static variables are also initialized with zero, – Nishant Aug 03 '15 at 09:48
  • @Nishant exactly. I've changed the wording to avoid the confusion. The exact terms of the standard is "variables with static storage duration" which covers global variables and static variables. – Christophe Aug 03 '15 at 09:53
2

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;

Nishant
  • 1,635
  • 1
  • 11
  • 24
2

Global variables are static storage variables and these are by default zero-initialized. For more information, please see the answer here.

Community
  • 1
  • 1
Itban Saeed
  • 1,660
  • 5
  • 25
  • 38
1

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 ]

mazhar islam
  • 5,561
  • 3
  • 20
  • 41