Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.6k views
in Technique[技术] by (71.8m points)

c - 'Initializer not constant' on global variable?

So I get the 'initializer element not constant' error when compiling the following code:

#include <stdlib.h>
#include <stdio.h>
#include <math.h>

float wl = 2.0f;
float k = 2.0f * (float) M_PI / wl;

int main ()
{
     //Do stuff
}

If I move "float k" inside the main method, there's no errors, but this isn't an option for me, because I NEED float k to be a global variable. Even if I change it to this:

const float wl = 2.0f;
const float k = 2.0f * (float) M_PI / wl;

the error still happens. How do I fix this?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

According to C99 standard:

§6.7.8 Initialization

  1. All the expressions in an initializer for an object that has static storage duration shall be constant expressions or string literals.

Using const doesn't help here because, in C, const variables are not really const. Check out this post for more details.


To work out, you can make wl constant by using preprocessor:

#define wl 2.0f

By doing this, 2.0f * (float) M_PI / wl can be a compile time constant.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...