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 t开发者_Python百科o 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?
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.
You can use enum
to achieve this:
enum { x = 123, y = x };
(x
and y
are typed in this case).
c only supports literals or other items know at compile that are unchangeable.
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;
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?
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:
- Literals
enum
constantssizeof
expressions- address expressions concerning functions
- address expressions concerning objects with static storage duration
and 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.
精彩评论