Hobbes
Hobbes

Reputation: 227

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

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?

Upvotes: 2

Views: 2607

Answers (2)

Bigger
Bigger

Reputation: 1970

Global consts don't work like that in C.

If a global scope variable needs protection against any further change, that's a sign you need to encapsulate it.

Create a protected_variable_setter and a getter. Make the setter known only to the file where the variable is initialized. Then access the variable only through the getter.

Upvotes: 1

KamilCuk
KamilCuk

Reputation: 141493

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

Upvotes: 2

Related Questions