2

I want to declare a global const variable that is defined at runtime. That is, I want to prompt the user for a value and assign it to a const global variable that I don't want to be modified during the execution of the program.

If I wanted a const variable in the main I could do

int tmp;
cin >> tmp;
const int var = tmp;

But if I want to use a global variable I can't because I have to declare it outside the main. For context, this is for high performance scientific computing. I want to define a set of physical constants that shouldn't change and that I need to access from anywhere. Is there any way I can do this?

songyuanyao
  • 169,198
  • 16
  • 310
  • 405
andrepd
  • 587
  • 6
  • 20

1 Answers1

3

Write an init function for it:

int init() {
    int tmp;
    cin >> tmp;
    return tmp;
}
const int var = init();
songyuanyao
  • 169,198
  • 16
  • 310
  • 405
  • I had to add inline keywords (added in C++ 17) to work. Still the only answer I found useful (solved my problem) googling for hour about this problem, thanks. – bolt Aug 15 '20 at 20:41