Closed. This question is off-topic。它当前不接受答案。
                            
                        
                    
                
                            
                                
                
                        
                            
                        
                    
                        
                            想改善这个问题吗? Update the question,因此它是on-topic,用于堆栈溢出。
                        
                        2年前关闭。
                                                                                            
                
        
我是新手,不胜感激。


  使用未声明的标识符“ 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
    }
}

最佳答案

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停止退出。这就是为什么您无法访问
其他块中的变量(除非内部循环未声明变量
同名)。例如,这将生成一个编译错误:

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标准之前,您无法编写x,因此必须声明
for(int i = 0; ...循环之前的变量。如今,大多数现代编译器都将C99用作默认值,这就是为什么您会看到一个
for中声明变量的很多答案。但是变量for()
仅在i循环中可见,因此相同的规则适用于示例
以上。请注意,这仅适用于for循环,无法执行for,会出现错误
从编译器。

也要注意分号,写

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


和做的一样

if(cond)
{
}

while(cond)
{
}

for(...)
{
}


这是因为C语法基本上说,在while(int c = getchar())ifwhile
您需要一个语句或一个语句块。 for是有效的声明
什么都不做。

我认为这些很难发现错误,因为当您阅读时,大脑经常会错过;
看线。

关于c - 使用声明的未声明的标识符“k”,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48855288/

10-11 21:59
查看更多