Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why won't gcc compile uninitialized global const?

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

like image 224
Baruch Avatar asked Sep 19 '25 22:09

Baruch


1 Answers

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...

like image 195
Anton Kovalenko Avatar answered Sep 23 '25 11:09

Anton Kovalenko