I am trying to learn C but I get an error in the following code.
If I use radius in volume I get an error: error #2069: Initializer must be constant.
#include <stdio.h>
#define PI (3.14)
/* Define radius*/
int radius = 10;
float volume = ( 4.0f / (3.0f * PI * radius) );
int main(void){
return 0;
}
But when I change radius with an actual number, it compiles just fine.
#include <stdio.h>
#define PI (3.14)
/* Define radius*/
int radius = 10;
float volume = ( 4.0f / (3.0f * PI * 10) );
int main(void){
return 0;
}
Why does this happen, and what can I do to make the first version work?
5 Answers
In C you cannot initialize global variables with non-constant expressions.
C99 Standard: Section 6.7.8:
All the expressions in an initializer for an object that has static storage duration shall be constant expressions or string literals.
In your example, volume is a global variable with static storage duration and radius is not a constant. Hence the error.
In C, you can only initialize a variable outside a function with constant expressions. int radius is not a constant expression.
A static object can't be initialized with a non-constant expression. In your example,
float volume = ( 4.0f / (3.0f * PI * radius) );
volume is a global variable and has static duration. So it can't be initialized with a non-constant expression.
However, if volume is a local variable then it can be initialized with a non-constant value in C99. So the following is allowed (non-constant initialization) in C99.
#include <stdio.h>
#define PI (3.14)
/* Define radius*/
int radius = 10;
int main(void){
float volume = ( 4.0f / (3.0f * PI * radius) );
return 0;
}
But the same is not valid in C90 in which all initalizers must be constant expressions.
A constant in this regard is something without a memory address. radius has a memory address, so it cannot be used for the initialization.
It is just C, not C++, so radius must be constant, but if you want it as a variable.
Define volume in main() as
#include <stdio.h>
#define PI (3.14)
/* Define radius*/
int radius = 10;
int main(void){
float volume = ( 4.0f / (3.0f * PI * radius) );
return 0;
}
Now, the error may vanish.