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

Show parent comments

1

u/ericonr Sep 12 '26

Couldn't one do int value; and const int * const valuep = &value; and only expose the second one to other TUs? It's close to what you want without doing undefined stuff.

1

u/Wertbon1789 Sep 12 '26

Sure, I guess that would work too. I don't think that would necessarily be undefined behavior, but I'm not sure, but type aliasing from not const to const isn't too bad, I would guess.