使用声明的未声明标识符'k'

-1 c int loops for-loop identifier

我是新手,非常感谢任何帮助.

使用未声明的标识符'k'

void initBricks(GWindow window)
{
    // print bricks
    for(int k = 0; k < ROWS; k++);
    {
        // int I have problem with

        int b = k;
        //coordinats
        int x = 2;
        int y = 10
    }
}
Run Code Online (Sandbox Code Playgroud)

Pab*_*blo 6

for循环后看分号:

for(int k = 0; k < ROWS; k++);
{
    // int I have problem with

    int b = k;
    //coordinats
    int x = 2;
    int y = 10
}
Run Code Online (Sandbox Code Playgroud)

是相同的

for(int k = 0; k < ROWS; k++)   //<-- no semicolon here
{
}

{
    // int I have problem with

    int b = k;
    //coordinats
    int x = 2;
    int y = 10
}
Run Code Online (Sandbox Code Playgroud)

k只在for循环块内有效,下一个块不知道k.

你必须写

for(int k = 0; k < ROWS; k++)   //<-- no semicolon here
{
    int b = k;
    //coordinats
    int x = 2;
    int y = 10
}
Run Code Online (Sandbox Code Playgroud)

在C中,变量的范围由块(花括号中的代码行)决定,你可以这样:

void foo(void)
{
    int x = 7;
    {
        int x = 9;
        printf("x = %d\n", x);
    }

    printf("x = %d\n", x);
}
Run Code Online (Sandbox Code Playgroud)

它会打印出来

9
7
Run Code Online (Sandbox Code Playgroud)

因为有两个x变量.的int x = 9在内部循环"覆盖"的x外部块的.内部循环x是与外部块不同的变量x,但是x当内部循环结束时内部循环停止退出.这就是为什么你不能从其他块访问变量的原因(除非内部循环不声明具有相同名称的变量).这将例如生成编译错误:

int foo(void)
{
    {
        int x = 9;
        printf("%d\n", x);
    }

    return x;
}
Run Code Online (Sandbox Code Playgroud)

你会得到这样的错误:

a.c: In function ‘foo’:
a.c:30:12: error: ‘x’ undeclared (first use in this function)
     return x;
            ^
a.c:30:12: note: each undeclared identifier is reported only once for each function it appears in
Run Code Online (Sandbox Code Playgroud)

下一个代码将编译

int foo(void)
{
    int x;
    {
        int x = 9;
        printf("%d\n", x);
    }

    return x;
}
Run Code Online (Sandbox Code Playgroud)

但你会得到这个警告

a.c: In function ‘foo’:
a.c:31:12: warning: ‘x’ is used uninitialized in this function [-Wuninitialized]
     return x;
            ^
Run Code Online (Sandbox Code Playgroud)

在C99标准之前你不能写for(int i = 0; ...,你必须在for循环之前声明变量.现在大多数现代编译器都使用C99作为默认值,这就是为什么你会看到很多答案声明变量的原因for().但是变量i只能在for循环中看到,所以相同的规则适用于上面的例子.请注意,这仅适用于for循环,while(int c = getchar())无法执行,您将从编译器中获得错误.

还要注意分号,写作

if(cond);
while(cond);
for(...);
Run Code Online (Sandbox Code Playgroud)

和做的一样

if(cond)
{
}

while(cond)
{
}

for(...)
{
}
Run Code Online (Sandbox Code Playgroud)

那是因为C语法基本上说,在一个if之后while,for 你需要一个语句或一个语句块.;是一个无效的声明.

在我看来,这些很难找到错误,因为;当你看到这条线时,大脑经常会错过.