Reputation: 1266
This code doesn't compile:
const int x = 123;
const int y = x;
It complains that "initializer element is not constant" for the y= line. Basically I want to have two const values, one defined in terms of the other. Is there a way to do this in C or do I have to use type-unsafe #defines or just write out the values literally as magic numbers?
Upvotes: 4
Views: 302
Reputation: 25495
c only supports literals or other items know at compile that are unchangeable.
Upvotes: 1
Reputation: 78903
Your y
is not a constant in the understanding of C but a const
qualified variable.
Compile time constant expressions as you want to use them may contain:
enum
constantssizeof
expressionsand may combine these mostly freely with the usual arithmetic, as long as the resulting type is compatible with the type of the left hand side.
Upvotes: 0
Reputation: 239011
You can use enum
to achieve this:
enum { x = 123, y = x };
(x
and y
are typed in this case).
Upvotes: 3
Reputation: 7159
C only supports literals as const initializers. So you will have to use some value to initialize your const, you cannot do it in terms of other variables that are const themselves.
However, this raises another important question. "const"-ness of a variable is known to the compiler while compiling, so why is this construction not allowed? ... Can some of the C experts please comment on this?
Upvotes: 0
Reputation: 1839
C only supports literals as const initializers. You can not initialize const with a variable.
But C does support
#define x 100
const int y = x;
Upvotes: 0
Reputation: 16240
When assigning const type you can only assign literals i.e.: 1, 2, 'a', 'b', etc. not variables like int x, float y, const int z, etc. Variables, despite the fact that your variable is really not variable (as it cannot change) is not acceptable. Instead you have to do:
const int x = 123;
const int y = 123;
or
#define x 123
const int y = 123;
The second one works, because the compiler will strip everywhere there is x and replace it with a literal before it is compiled.
Upvotes: 8