Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why isn't it possible in C to initialize a constant with another constant? [duplicate]

Tags:

c

gcc

Compiling the following code with gcc.

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 compile error like below

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

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

I used gcc 4.9.2

like image 237
rnstlr Avatar asked Apr 30 '15 07:04

rnstlr


1 Answers

const variable can be initalized with constant values (constant expressions).


  • In C

At compilation time, i + 1 is not a constant expression.

FWIW, even

const int n = i;

will give you error, because, even if declared as const, i cannot be used as constant expression to be used as an initalizer to another const.


  • In C++

const variables are tread as constant expression if they are initialized with constant expressions. So, this is allowed.

like image 137
Sourav Ghosh Avatar answered Sep 18 '22 15:09

Sourav Ghosh