const与constexpr的区别

首先我们可以认为const代表“只读”,而constexpr代表“常量”。

常量意味着不能被修改,而只读则不一定:

#include <iostream>
using namespace std;
int main()
{
    int a = 10;
    const int & b = a;
    cout << b << endl;
    a = 20;
    cout << b << endl;
}

输出为:

10
20

尽管b为只读,但我们仍然可以通过修改a的值来改变b的值

const

由于const仅代表只读,所以一般情况下用const声明为只读变量,其本质还是变量;当我们想要声明只读常量时只需在后面加上“= 数字”

const int x;//只读变量
const int y = 5;//只读常量

而我们知道array是一个固定大小的数组,其大小在编译时就确定了,所以确定其大小的量只能为常量

void dis_1(const int x){
    array <int,x> myarr{1,2,3,4,5};
    cout << myarr[1] << endl;
}
void dis_2(){
    const int x = 5;
    array <int,x> myarr{1,2,3,4,5};
    cout << myarr[1] << endl;
}
int main()
{
   dis_1(5);
   dis_2();
}

运行上面的代码会发现dis_1()运行出错,dis_2()能够正常运行,这是因为x在dis_1中为只读变量,而在dis_2中由于后面有了=5所以是只读常量,因此可以正常运行

constexpr

constexpr修饰常量或常量表达式,常量表达式就是多个常量组成的表达式,由于全部是常量,所以编译器在编译时就会计算出结果,而在运行时直接调用,这避免了多次重复的运算,从而提高了代码的运行速度

constexpr修饰常量或常量表达式

constexpr int num = 1;
constexpr int num = 1 + 2 + 3;

constexpr修饰函数

对于constexpr修饰的函数,编译器会认为该函数的返回值为常量,但是该函数需要满足几点要求

  • 函数必须有返回值,即函数不是void
  • 整个函数的函数体中,除了可以包含 using 指令、typedef 语句以及 static_assert 断言外,只能包含一个return语句
  • 返回的表达式必须是常量表达式
  • 函数使用前一定要定义
constexpr int display(int x) {
    int ret = 1 + 2 + x;//错误,只能有return
    return ret;//应写为return 1 + 2 + x
}

constexpr int display(int x){
    return num + x;//错误,num非常量
}

 由于constexpr修饰的函数返回常量,所以可以用来指定array数组的大小

constexpr int sqr1(int arg){
    return arg * arg;
}
const int sqr2(int arg){
    return arg * arg;
}
int main()
{
    array<int, sqr1(10)> a;
    array<int, sqr2(10)> b;
    return 0;
}

上述代码中a能够被初始化,b不能被初始化

除了上面特殊提及的场景外,在大部分实际场景中,const 和 constexpr 是可以混用的

const int a = 5 + 4;
constexpr int a = 5 + 4;

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值