区分C++常量表达式、const、constexpr(附代码)


本文摘自PHP中文网,作者php是最好的语言,侵删。

常量表达式是指值不会改变且在编译过程中就能够得到计算结果的表达式,能在编译时求值的表达式。

例1:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

#include <iostream>

using namespace std;

 

int main()

{

     

    const int a1 = 10;           // a1是常量表达式。

 

    const int a2 = a1 + 20;      // a2是常量表达式

 

    int a3 = 5;                  // a3不是常量表达式

 

    const int a4 = a3;           // a4不是常量表达式,因为a3程序的执行到达其所在的声明处时才初始化,所以变量a4的值程序运行时才知道。但编译没问题!

 

    return 0;

}

以上代码可正常编译。

说明了const声明的不一定就是常量表达式!

C++11新标准规定,允许将变量声明为constexpr 类型以便由编译器来验证变量的值是否是常量表达式。constexpr 指定符声明可以在编译时求得函数或变量的值,声明为constexpr的变量一定是一个常量,而且必须用常量表达式来进行初始化。

例2:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

#include <iostream>

using namespace std;

 

int main()

{

     

    const int a1 = 10;           // a1是常量表达式。

 

    const int a2 = a1 + 20;      // a2是常量表达式

 

    int a3 = 5;                  // a3不是常量表达式

 

    constexpr int a4 = a3;           // a4不是常量表达式,因为a3程序的执行到达其所在的声明处时才初始化,所以变量a4的值程序运行时才知道。编译报错!

 

    return 0;

}

constexpr int a4 = a3; 编译将报错!

例3:

1.png

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

#include <iostream>

using namespace std;

 

int main()

{

     

    const int a1 = 10;           // a1是常量表达式。

    const int a2 = a1 + 20;      // a2是常量表达式

    int a3 = 5;                  // a3不是常量表达式

    const int a4 = a3;           //   a4不是常量表达式,因为a3程序的执行到达其所在的声明处时才初始化,所以变量a4的值程序运行时才知道。编译报错!

 

    char arr1[a2];   // 没问题

    char arr2['y'];  // 没问题,'y'的ASCII码为121,相当于 char arr2[121];

 

    char arr3[a4];   // 编译报错,因为a4不是常量表达式

 

 

    return 0;

}

相关文章:

分享多个C#常用正则表达式的实例

PHP定义常量是,const和define的区别

以上就是区分C++常量表达式、const、constexpr(附代码)的详细内容!

相关阅读 >>

C++运算符中不能重载的是哪些

const在C++中的意思

C++ 图解层序遍历和逐层打印智能指针建造的二叉树

C++语言标识符的命名规则是什么?

C++如何从函数返回数组

C++输出二维字符矩阵对齐

C++中字符串比较函数strcmp怎么用?

C++中main函数的返回值类型是什么

C++笔试题之实现简单记录错误功能

如何安装visual C++ 6.0

更多相关阅读请进入《C++》频道 >>



打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...