4

When I try to compile the following with g++:

const int zero;

int main()
{
  return 0;
}

I get an error about an uninitialized const 'zero'. I thought that global variables were default initialized to 0 [1] ? Why isn't this the case here?
VS compiles this fine.

[1] For example, see https://stackoverflow.com/a/10927293/331785

Community
  • 1
  • 1
Baruch
  • 20,590
  • 28
  • 126
  • 201
  • 1
    I just realized that `gcc` does compile it. It is `g++` that doesn't. Why is that? Is the rule about global variables being initialized to 0 not part of the c++ standard? – Baruch Jan 28 '13 at 18:43
  • 1
    [Some argue](http://yosefk.com/c++fqa/fqa.html#fqa-21.1) than in C++ random things compile and other random things don't. I don't think even the reference to the standard gives any idea on *why* it should be disallowed. – Anton Kovalenko Jan 28 '13 at 19:03

2 Answers2

7

My gcc is slightly more verbose:

$ g++ zeroconst.c
zeroconst.c:1:11: error: uninitialized const ‘zero’ [-fpermissive]

We see that -fpermissive option will allow this to compile.

See this question on uninitialized const for a reference to C++ standard (the problem is C++-specific).

As cited at GCC wiki:

As mandated by the C++ standard (8.5 [decl.init], para 9 in C++03, para 6 in C++0x), G++ does not allows objects of const-qualified type to be default initialized unless the type has a user-declared default constructor. Code that fails to compile can be fixed by providing an initializer...

Community
  • 1
  • 1
Anton Kovalenko
  • 20,999
  • 2
  • 37
  • 69
  • 1
    Yes, but that doesn't explain why it is even an error under the default configuration. It seems perfectly legal since global variables *are* initialized! – Baruch Jan 28 '13 at 18:42
  • @baruch added link to a question with the answer quoting the `C++` standard (as of C, it is valid and it compiles) – Anton Kovalenko Jan 28 '13 at 18:44
-1

G++ requires that you initialize your constant during definition.

Aniket Inge
  • 25,375
  • 5
  • 50
  • 78