使用声明[关闭]的未声明标识符'k'

问题描述 投票:-1回答:1

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

使用未声明的标识符'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
    }
}
c loops for-loop int identifier
1个回答
6
投票

看看for循环后面的分号:

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

    int b = k;
    //coordinats
    int x = 2;
    int y = 10
}

是相同的

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
}

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

你必须写

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

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

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

    printf("x = %d\n", x);
}

它会打印出来

9
7

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

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

    return x;
}

你会得到这样的错误:

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

下一个代码将编译

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

    return x;
}

但你会得到这个警告

a.c: In function ‘foo’:
a.c:31:12: warning: ‘x’ is used uninitialized in this function [-Wuninitialized]
     return x;
            ^

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

还要注意分号,写作

if(cond);
while(cond);
for(...);

和做的一样

if(cond)
{
}

while(cond)
{
}

for(...)
{
}

这是因为C语法基本上说,在ifwhilefor之后你需要一个陈述或一块陈述。 ;是一个无效的声明。

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

© www.soinside.com 2019 - 2024. All rights reserved.