#include"pch.h"
#include<iostream>
using namespace std;
constexpr int show(const int x)//在dev C++中,形参不能为int;须为const int;但在VS2017中均可
{
//在dev C++中constexpr函数,只能有一个语句,即return+其他;
//但是在,vs2017中可以有多行语句;
return x;
}
int f = 2;
//全局变量在编译的时候就可以确定
//局部变量一般是运行时分配的,通常在栈上,所以地址确定不了
int main()
{
//constexpr 关键字使得代码在编译过程中,
//如果编译器对于某个表达式已经得到足够多的信息,
//那么编译器会在编译器一结束就把该表达式的结果求出来。
//即对于无 constexpr 关键字的表达式是在运行期执行,
//对于有 constexpr 关键字的表达式是在编译期执行
//总结:constexpr修饰的函数,不能依赖任何运行期的信息,
//不要定义任何变量常量,并且必须尽量简单,
//要不就会编译不过或告警(坑)
constexpr int a = 23;
constexpr int *b = &f;//f是全局变量,在编译时,能确定其地址,故可以当做常量使用;
//constexpr int *y = &a;//
const int c = 3;
constexpr int d = a;//a是常量,可以赋值给d
//constexpr int d = c;//此语句有错误,c是变量,不能做常量使用
constexpr int &x = f;
constexpr int e = show(c);
//show(x)——x可以为常数,可以为const int变量,可以是constexpr int变量
//constexpr int d = c + 3;//编译错误,因为c是变量,不能作为常量值,
cout << "d=" << d << endl;
cout << "e=" << e << endl;
}
关键字constexpr的理解
最新推荐文章于 2024-04-21 21:37:50 发布