const 和 constexpr差别
时间: 2023-10-13 08:04:15 浏览: 122
const和constexpr都是用来定义常量的关键字,但是它们之间有一些差别。
1. const定义的变量在编译时并不要求能够被算出,也就是说可以由变量赋值。而constexpr定义的变量,在编译时就能被算出,只能由常量表达式赋值。例如:
- const int i = x * x; 在这种情况下,x的值是在运行时才能确定的,所以x*x不是常量表达式。
- constexpr int j = x * x; 在这种情况下,编译器会报错,因为x*x不是常量表达式。
2. const修饰的变量可以被常量表达式初始化,也可以被编译期不能计算出值的表达式初始化。而constexpr修饰的变量一定要用常量表达式初始化。例如:
- const int i = x * x; 这是正确的,因为x*x是常量表达式。
- constexpr int j = i; 这是错误的,因为i不是常量表达式。
3. const修饰的变量可以用于指定数组大小,也可以用于指定函数的返回值。而constexpr修饰的变量一定可以用于指定数组的大小。例如:
- int a[i]; 这是错误的,因为i不是常量表达式。
- int b[j]; 这是正确的,因为j是常量表达式。
总结起来,constexpr比const更加常量一点,它要求在编译时就能够被算出,并且一定是常量,可以用于指定数组的大小。而const可以在运行时才能被赋值,并且可以被编译期不能计算出值的表达式初始化。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* *2* [C++ const 和 constexpr的区别](https://blog.csdn.net/m0_51551385/article/details/123271482)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"]
- *3* [C++中 const和constexpr的区别](https://blog.csdn.net/weixin_41290863/article/details/121915270)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"]
[ .reference_list ]
阅读全文
相关推荐


















