r/C_Programming • • Sep 11 '26

Question Unmodifiable globals initialized from functions?

Right now I'm trying to use Windows's SYSTEM_INFO to initialize 2 global constants, but global constants can only be initialized with constant expressions so this cannot be done.

Is there a way I can have "read-only" global variables that can be initialized from functions?

6 Upvotes

40 comments sorted by

View all comments

5

u/pjl1967 Sep 11 '26

In C, no.

1

u/heavymetalmixer Sep 12 '26

My "gheto solution" now is to use a short function that returns the value instead of a variable storing that value. It's slower yeah, but it works.

2

u/septum-funk Sep 12 '26

this should be inlined by the compiler anyway

0

u/tstanisl Sep 12 '26

constexpr is already in C

3

u/heavymetalmixer Sep 12 '26 edited Sep 12 '26

Only since C23, and that's for compile-time constants not runtime ones.

2

u/pjl1967 Sep 12 '26

Functions can’t be constexpr in C.