Why is it not possible in C to initialize a constant with another constant?

Compiling the following code with gcc.

The code:

#include <stdio.h> const int i = 10; const int n = i+1; int main() { printf("%i\n", i); printf("%i\n", n); } 

Error:

I get a compilation error as below

 test.c:3:5: error: initializer element is not constant const int n = i+1; ^ 

Compiling with g ++ works fine and prints 10 and 11.

I used gcc 4.9.2

+5
source share
2 answers

const variable can be initialized with constant values ​​(constant expressions).


  • In C

At compile time, i + 1 not a constant expression.

Fwiw even

 const int n = i; 

will give you an error, because even if declared as const , i cannot be used as a constant expression, which will be used as an initializer for another const .


  • In C++

const variables are protectors as a constant expression if they are initialized by constant expressions. Therefore, it is allowed.

+1
source

static variables must be initialized with a constant.
The C ++ compiler will compile it, because in C ++ const qualified variables are constants. In C, const qualified variables are not constant, and the C compiler raises an error.

0
source

All Articles