tips for constexpr and Constant Expressions

闻枫
2023-12-01

A constant expression is an expression whose value cannot change and that can be evaluated at compile time.

A typical characteristic: the constant express will be evaluated at compile time, not at run time.

So when we use it and pay attention to it.. If we are implicitly to know what it is, don't use it.

for instant:

#include <iostream>

int main()
{
int m = 10;
constexpr int m2 = m;
std::cout << m2 << std::endl;
return 0;
}

when we compile it, it can't work it out.? Why?

It's easy to explain it. Because of the "m" variables are not usable when compiling. The compiler don't recognize it.. 

your compiler will tell you it's not usable in constant expression. Mine tell me that.. But if we told the compiler that "m" is a ”const int“

It will work out or to be compiled successfully..

so let we made some changes:

#include <iostream>
int main()
{
const m = 10;
constexpr int m2 = m;
std::cout << m2 << std::endl;
return 0;
}

I'm a cookie. There are a lot of concepts in the C++ world. It baffles me...

for example: const definition contain the "low-level const" and "top-level const". if they are both existed in the expression or statements, we can igonre the "top-level const".

How to distinguish it? C++ prime tells me that " Top-level const can appear in any object type, ...., Low-level const appears in the base type of compound types such as pointers or references. Note the pointer types, unlike most other types, can have both top-level and low-level const independently."

Another words: "... Like an object defined outside any function, these special local objects also have fixed addresses. Therefore, a constexpr reference may be bound to, and a constexpr pointer may address, such variables. "

 类似资料:

相关阅读

相关文章

相关问答