使用static,const,constexpr进行全局声明/初始化

All*_*nzi 5 c++ c++11

在C++或C++ 11中,对于以下声明//初始化,

// global scope
const int a = 1; // line 1
static const int b = 2; // line 2
constexpr int c = 3;  // line 3
static constexpr int d = 4; // line 4
constexpr int e = a + b + c*d; // line 5
static constexpr int f = a - b - c*d; // line 6
Run Code Online (Sandbox Code Playgroud)

这个问题说在文件范围内,C++中第1行和第2行之间没有区别.3号线和4号线怎么样?

4号线和5号线之间是否存在差异?

5号线和6号线之间有区别吗?

Bap*_*cht 7

不,不应该有任何区别(当然除了它们的值)因为constexpr和const意味着内部联系:

[C++11: 3.5/3]: 具有命名空间作用域(3.3.6)的名称具有内部链接(如果它的名称)

  • 显式声明的变量,函数或函数模板static; 要么,
  • 即明确地声明的变量 constconstexpr既不显式声明extern也不先前声明为具有外部连接 ; 要么
  • 匿名联盟的数据成员.