2

Could you tell me what's wrong? When I try to compile it I see an error:Initializer element is not constant. It's about 2nd line, probably going about x.

float x = 10;
float d = x/100;
float a = 0;
Editt
  • 47
  • 1
  • 1
  • 4
  • 1
    You need a `main`, don't you? – ForceBru Mar 12 '16 at 20:31
  • Compiler only tells you that you can not initialize a global variable with something that is not constant... i.e. not with another variable. – Laurent H. Mar 12 '16 at 20:34
  • But the variable is constant in all the program – Editt Mar 12 '16 at 21:29
  • @Editt Those variables are not explicitly defined as constants, and `const` won't work either (see [this question](https://stackoverflow.com/questions/4024318/why-do-most-c-developers-use-define-instead-of-const?lq=1)). C's `const` does not behave the way you might expect. – Mac O'Brien Mar 12 '16 at 23:39

2 Answers2

9

In C, global variables can be initialized using only constants. Hence, the line

float d = x/100;

is not correct.

You can use preprocessor macros to accomplish your goal.

#define CONSTANT 10.0

float x = CONSTANT;
float d = CONSTANT/100;
float a = 0;
R Sahu
  • 204,454
  • 14
  • 159
  • 270
4

Initializers outside functions must be constants, you are not allowed to use x/100 because x could be undefined in this phase of unit translation (compilation).
As a workaround you can use a symbol to use for both declarations:

#define Value 10.0
float x = Value;
float d = Value/100;
float a = 0;

Anyway you can use this code inside a function for C99-C11 standards:

void foo(void)
{
    float x = 10;      //Here works
    float d = x/100;
    float a = 0;

    ...
}

P.S. I wrote the same answer as Sahu in the same time. Anyway I would point out the reasons explained in the first part.

Frankie_C
  • 4,764
  • 1
  • 13
  • 30