'for'循环初始声明中的静态变量

Sun*_*lly 4 c static c99

想知道为什么我不能在for循环初始化中声明一个静态变量,如下所示,

for(static int i = 0;;)
Run Code Online (Sandbox Code Playgroud)

用我的C99标准编译器编译上面的循环语句代码我看到下面的错误,

error: declaration of static variable ‘i’ in ‘for’ loop initial declaration
Run Code Online (Sandbox Code Playgroud)

chu*_*ica 6

C不允许

C11dr 6.8.5 迭代语句 3

"声明的声明部分for只应声明具有存储类autoregister"的对象的标识符.

(不是static)


通常,代码不会受益于能够拥有迭代器的形式static.


存储类说明符:

typedef
extern
static
_Thread_local
auto
register
Run Code Online (Sandbox Code Playgroud)


eri*_*cbn 5

在声明中声明变量的目的for是将其范围缩小到循环块.

// i does not exist here
for (int i = 0;;) {
  // i exists here
}
// i does not exist here
Run Code Online (Sandbox Code Playgroud)

当您将局部变量声明为static并初始化它时,初始化仅在首次运行代码时完成一次.

{
  static int i = 0; // i will be set to 0 the first time this is called
  i++;
}
Run Code Online (Sandbox Code Playgroud)

因此,在循环声明中初始化forstatic变量循环只会被初始化一次!

// i will not be initialized to 0 the second time this loop runs and we cannot
// initialize it here, before the loop block
for (static int i = 0;;) {
  // ...
}
Run Code Online (Sandbox Code Playgroud)