Search code examples
cinitializationconstants

Why const variable need not to be initialized in C?


const variables in C++ must be initialized means uninitialized const variable isn't possible & it is a compiler error. But why it is not same in C language also? Consider following program that compiles fine C:

#include <stdio.h>
int main()
{
    const int a;
}

What is the reason to allow uninitialized const? Wouldn't it be nice If C also follows same rule as C++ does? Is it due to performance concerns that local const variable needs to be initialized every time when a function is called & initialization takes time?


Solution

  • The difference probably stems, among other things, from a significantly more relaxed approach to initialization in C language in general, not only with regard to const objects. For example, this code is illegal in C++

    goto over;
    int a = 5;
    over:;
    

    because it jumps into scope of a bypassing its initialization. Meanwhile in C this code is perfectly legal, with variable a having indeterminate value at over:.

    The same logic applies to your const int a declaration. C language simply believes that an uninitialized object is not a big deal, even in situations where it is no longer possible to set it to a determinate value later.

    The primary reason for stricter initialization requirements in C++ is introduction of non-trivial initialization (constructors) into the language, i.e. initialization that cannot be meaningfully bypassed. Scalar objects and their initialization in C++ just tagged along as small part of a much broader concept.

    Wouldn't it be nice If C also follows same rule as C++ does?

    I don't see it. C and C++ are substantially different languages. And they treat const quite differently as well.