wcroughan
wcroughan

Reputation: 154

const variable in function assigned at run-time

I recently realized I have the following in my C++ code, and it compiles and runs without any problems.

void MyClass::foo(int a) {
    const double x = a;
    ...
    //do stuff with x
    ...
}

My question: I thought const variables were assigned a value at compile time and this would have given me a compile error, though in this case it obviously is assigned at runtime. Is the const specifier here being ignored? Or is there something else more complicated going on? Should I remove the const specifier?

Upvotes: 2

Views: 841

Answers (1)

YSC
YSC

Reputation: 40070

Constant variables are assigned a value when initialized (at run-time), and cannot be modified afterwards. References and pointers to constant variables can only be used to read from those variables, the underlying variable being constant or not.

I thought const variables were assigned a value at compile time

What you are describing are C++11 constexpr variables.

Should I remove the const specifier?

No. You should make everything const unless you specifically need it to not be const.

Upvotes: 2

Related Questions