简短的回答:
const 承诺一旦设置,您将不会尝试修改该值。
static 变量意味着对象的生命周期是程序的整个执行过程,并且它的值仅在程序启动前初始化一次。如果您没有为它们显式设置值,则所有静态都将被初始化。静态初始化的方式和时间是未指定。
C99 从 C++ 借用了 const 的用法。另一方面,static 一直是许多争论的根源(两种语言),因为它经常混淆语义。
此外,在 C++11 之前的 C++0x 中,不推荐使用 static 关键字来声明命名空间范围内的对象。由于各种原因,此弃用已在 C++11 中删除(请参阅here)。
更长的答案:比您想知道的更多关键字(直接来自标准):
C99
#include <fenv.h>
#pragma STDC FENV_ACCESS ON
/* file scope, static storage, internal linkage */
static int i1; // tentative definition, internal linkage
extern int i1; // tentative definition, internal linkage
int i2; // external linkage, automatic duration (effectively lifetime of program)
int *p = (int []){2, 4}; // unnamed array has static storage
/* effect on string literals */
char *s = "/tmp/fileXXXXXX"; // static storage always, may not be modifiable
char *p = (char []){"/tmp/fileXXXXXX"}; // static, modifiable
const char *cp = (const char []){"/tmp/fileXXXXXX"} // static, non-modifiable
void f(int m)
{
static int vla[ m ]; // err
float w[] = { 0.0/0.0 }; // raises an exception
/* block scope, static storage, no-linkage */
static float x = 0.0/0.0; // does not raise an exception
/* ... */
/* effect on string literals */
char *s = "/tmp/fileXXXXXX"; // static storage always, may not be modifiable
char *p = (char []){"/tmp/fileXXXXXX"}; // automatic storage, modifiable
const char *cp = (const char []){"/tmp/fileXXXXXX"} // automatic storage, non-modifiable
}
inline void bar(void)
{
const static int x = 42; // ok
// Note: Since an inline definition is distinct from the
// corresponding external definition and from any other
// corresponding inline definitions in other translation
// units, all corresponding objects with static storage
// duration are also distinct in each of the definitions
static int y = -42; // error, inline function definition
}
// the last declaration also specifies that the argument
// corresponding to a in any call to f must be a non-null
// pointer to the first of at least three arrays of 5 doubles
void f(double a[static 3][5]);
static void g(void); // internal linkage
C++
除了简短回答中提到的以外,大部分情况下具有相同的语义。此外,没有参数限定statics。
extern "C" {
static void f4(); // the name of the function f4 has
// internal linkage (not C language
// linkage) and the function’s type
// has C language linkage.
}
class S {
mutable static int i; // err
mutable static int j; // err
static int k; // ok, all instances share the same member
};
inline void bar(void)
{
const static int x = 42; // ok
static int y = -42; // ok
}
我在这里省略了 C++ 的static 的更多细微差别。看看一本书或标准。