Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ Assign a const value at run-time?

I have a constant value that never changes during run-time, but is impossible to know until run-time.

Is there a way to declare a constant (either as a member of a class or not) without defining it and also assign a computed value once (and only once) it is determined; or am I going to have to resort to a non-const declaration and use coding S & Ps (ALL_CAPS variables names, static declaration if in a class, etc.) to try and keep it from changing?

CLARIFICATION:

Though these are good answers, the real-world situation I have is more complicated:

The program has a main loop that continually runs between processing and rendering; the user can set required options and once they are set they will never change until the program is restart. An "Initialize" function is set up for anything that can be determined before the main loop, but values that are dependent on user interaction must be performed in the middle of the loop during the processing phase. (At the moment, persistent data storage techniques come to mind...)

like image 501
Casey Avatar asked Jan 03 '13 01:01

Casey


People also ask

How to modify a const variable in C/C++?

How to modify a const variable in C? In C or C++, we can use the constant variables. The constant variable values cannot be changed after its initialization. In this section we will see how to change the value of some constant variables. If we want to change the value of constant variable, it will generate compile time error.

What are run time constants in C++?

These are the constants whose respective values can only be known or computed at the time of running of source code. Run time Constants are a bit slower than compile-time constants but are more flexible than compile-time constants. However, once it is initialized, the value of these constants can’t be changed.

How to initialize a const field at compile time?

A field marked as const can be initialized only at compile time. You need to initialize a field at runtime to a valid value, not at compile time. This field must then act as if it were a constant field for the rest of the application’s life. When declaring a constant value in your code, there are two choices.

How to create a constant in C?

To create a constant in C, put the keyword const before or after the type of the variable: These both examples are correct declarations. We need to do the initialization immediately . This is done on the same row with the declaration, because we cannot modify the value later. If you miss the initialization you should get a warning (not an error).


1 Answers

Something like this?

const int x = calcConstant();

If it's a class member, then use the constructor initialisation list, as in Yuushi's answer.

like image 114
Oliver Charlesworth Avatar answered Oct 05 '22 01:10

Oliver Charlesworth