Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

345
Vistas
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?

over 4 years ago · Santiago Trujillo
3 Respuestas
Responde la pregunta

0

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.

over 4 years ago · Santiago Trujillo Denunciar

0

History.

const was specified in C++ from its beginning and the use met that language's goals. const was later specified in C but with a related but different meaning to minimize exiting C code compatibility issues.

Since C began without const, its later inclusion is more like a read-only modifier than a constant one. This allowed existing compilers to essential treat const as nothing for writing to a const is undefined behavior. Newer compilers/code could take advantage that const provides.

const int a;
a = 5;  // problem in C as code attempts to write `a`

// Really should be `const char *fred`, but allowed for backwards compatibility.
char *fred = "sally";  

C++ took a stronger approach and demands the initialization.

See also const in C vs const in C++

over 4 years ago · Santiago Trujillo Denunciar

0

Because C is absolutely confident in the programmer and does allow him to do a lot of things including stupid ones : int *x = NULL; x[4] = 12; will be compiled without error and even without warnings by many compilers.

More precisely, const is just a promise that programmer does that the variable should not be modified, and that compiler could considere it as constant if is can help optimizations. But compiler will never enforce any run time rules to forbid to change a const value :

const a = 1;
int *ix = (int *) &a;
*ix = 2;
printf("a=%d\n", a); /* UB : could print 1 or 2 */

will be compiled without a warning. But it will invoke undefined behaviour because you modified an object declared as const.

I believe that not initializing const variables is allowed simply because current C specification does not forbid it ! In former versions, initialization has always be optional. Maybe future versions could force initialization for automatic variables

Anyway a global or static const variable is in fact automatically initialized (per C language specification 6.7.9 10) : If an object that has static or thread storage duration is not initialized explicitly, then: ... if it has arithmetic type, it is initialized to (positive or unsigned) zero; ...

So static const a; is perfectly valid as is const a if a is global and in those case a=0.

over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda