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
const
variable can be initalized with constant values (constant expressions).
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
.
C++
const
variables are tread as constant expression if they are initialized with constant expressions. So, this is allowed.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With