7

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

Dharma
  • 2,965
  • 3
  • 20
  • 36
rnstlr
  • 1,354
  • 11
  • 17

2 Answers2

1

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.

Sourav Ghosh
  • 130,437
  • 16
  • 177
  • 247
0

static variables need to be initialized with a constant.
A C++ compiler will compile it because in C++ const qualified variables are constants. In C, const qualified variables are not constant and a C compiler will raise an error.

haccks
  • 100,941
  • 24
  • 163
  • 252
  • 1
    But `g++` computes `i+1` it at compile time apparently. – Thilo Apr 30 '15 at 07:57
  • 4
    @Thilo g++ is a C++ compiler and in C++ the rules for constants are different. In C++ a constant can be initialized with a value evaluated at runtime. Const in c++ means that once initialized you cannot change its value any more. – rozina Apr 30 '15 at 08:00
  • @rozina: But that is not the case here. In this case (for C++), `i + 1` is evaluated at compile time. `i`, `i + 1`, and `n` are all compile time constant expressions in this code. – Benjamin Lindley Apr 30 '15 at 08:05
  • 2
    This is wrong. It has nothing to do with const. extern and static variables are initialised before main () starts, and their values must be constant expressions. In C, unlike C++, extern const variables don't count as "constant" as far as "constant expressions" are concerned. You can initialise a const local variable any way you like. – gnasher729 Apr 30 '15 at 08:24