您的位置:首页 > 其它

error C2099: initializer is not a constant

2010-04-08 16:05 465 查看
in file main.c there is a code.
here is the code:
short a=5;
short b=a;
void main()
{
}


The initialization value must be a compile time constant. a is a
variable. Even if you defined a as const short, it is still not a
compile time constant.
解决方案

Your options for compile time constant initialization goes beyond hard-coded
values: You may initialize it to some macro's value (#define BOOOO_HISSSS)
or a specific enum value. The enum hackonly works for int.

With variables you can of course get around it by simply assigning after
declaring(instead of all-in-one initialization). The real problem rears it's
ugly head when you want to inizialize a const with somevalue based another
const.

Are there any other ways besides setting them to a macro or enum?

i.e.
const int i = 1;
const int j = i + 100 // error C2099

enum Name_Does_Not_Matter
{
bar = 5
};
const int foo = bar + 10 // Success!! foo is initialized to 15


------------------msdn上的样例和解释---------------------

C2099 can also occur because the compiler is not able to perform constant folding on an expression under /fp:strict because the floating point precision environment settings (see _controlfp_s for more information) may differ from compile to run time.

When constant folding fails, the compiler invokes dynamic initialization, which is not allowed in C.

To resolve this error, compile the module as a .cpp file or simplify the expression.

For more information, see /fp (Specify Floating-Point Behavior).

// C2099_2.c
// compile with: /fp:strict /c
float X = 2.0 - 1.0;   // C2099
float X2 = 1.0;   // OK


或者

This error is issued only by the C compiler and occurs only for non-automatic variables. The compiler initializes non-automatic variables at the start of the program and the values they are initialized with must be constant.

// C2099.c
int j;
int *p;
j = *p;   // C2099 *p is not a constant


或者

int i, j;
int *p;
j = i();    // error, i() is not constant
j = *p;     // error, *p is not a constant
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: