tips for constexpr and Constant Expressions

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. "

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值