-4

In C you can do this:

static const int a;

int main(){}

And it seems to be fine. C99 §6.7.8p10 says:

If an object that has static storage duration is not initialized explicitly, then:

— if it has arithmetic type, it is initialized to (positive or unsigned) zero;

Similarly C++14 §3.6.2p2 says:

Variables with static storage duration (3.7.1) or thread storage duration (3.7.2) shall be zero-initialized (8.5) before any other initialization takes place.

The difference is in C++14 it needs an initializer §8.5p7:

If a program calls for the default initialization of an object of a const-qualified type T, T shall be a class type with a user-provided default constructor.

So I'm asking why is an initializer required in C++? No initializer is required if a is not const, so what difference does const make here that would make no initializer bad?

too honest for this site
  • 11,417
  • 3
  • 27
  • 49

2 Answers2

0

In the general case of a class type object, zero-initialization may not yield a valid object. And if such a class has no default constructor, then a static const of that type without an initializer, would produce an invalid object.

The current rules just don't add an exception for types where zero-initialization is good enough.

An extra language feature to support zero constants would complicate things for no real gain.

Cheers and hth. - Alf
  • 135,616
  • 15
  • 192
  • 304
-1

C is not a very safe language. In C, an initializer is not required for a const object. Meaning you can do this:

int main()
{
    const int a;
}

Oops. a has automatic storage duration, so it has an indeterminate value. And you can't change it later...

Now let's say you allowed this feature. Would it make sense? Well unlike C, C++ has a concept called constant initialization that is sometimes performed instead of zero initialization. But what do you expect the value of a to have? Indeterminate value? It can't be zero since we just said that doesn't happen!

If you want a to be zero, then just say so. Don't rely on implicit rules of the language which (in C's case) are inconsistent. That's bad for readability and maintainability.

  • The question is about a **file scope** variable, not an auto variable. File scope `int` variables get initialized to 0, so all this talk about indeterminate values is irrelevant. – Pete Becker Jun 06 '16 at 15:07