开发者

const values in C

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:

  1. Literals
  2. enum constants
  3. sizeof expressions
  4. address expressions concerning functions
  5. 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜