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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With