Home > database >  How to declare a global const variable and initialize it with a function in C?
How to declare a global const variable and initialize it with a function in C?

Time:03-25

I would like to declare a constant global variable and initialize it with a function. The problem is, I can't use my function to initialize it because a function call is not a compiler-time constant, but I also can't split the declaration and the initialization as it is a const variable.

For example, the following codes are invalid.

#include <stdio.h>

int my_function(void){
    return 42;
}

const int const_variable = my_function();//invalid: my_function() is not
                                         //a compiler-time constant

/*main() here*/
#include <stdio.h>

const int const_variable;
const_variable = 10;//invalid: can't modify a const-qualified type (const int)

/*main() here*/

I looked for some answers. I saw that some people suggested the use of pointers to modify the value of a const variable after its declaration, but this could cause severe readability, portability and debugging problems.

Is there any simple, portable way to solve my problem?

CodePudding user response:

How to declare a global const variable and initialize it with a function in C?

There is no way. It is not possible.

Is there any simple, portable way to solve my problem?

No.

You can use a macro #define MY_FUNCTION() (42).

You can write a separate program, that uses that C function (or is written in a completely different language), that generates C source code with that constant and that generated source code is then compiled with your project.

Or you can switch to a different programming language with more features, for example Rust, D, C .

  • Related