简体   繁体   中英

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?

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM