Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initializer must be constant

Tags:

c

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?

like image 535
intelis Avatar asked Oct 27 '25 01:10

intelis


1 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.

like image 132
Alok Save Avatar answered Oct 29 '25 17:10

Alok Save