Closed. This question is off-topic。它当前不接受答案。
想改善这个问题吗? Update the question,因此它是on-topic,用于堆栈溢出。
2年前关闭。
我是新手,不胜感激。
使用未声明的标识符“ k”
是相同的
了解
你将不得不写
在C语言中,变量的范围由代码块决定(代码中的代码行
花括号),您可以使用以下命令:
它会打印
因为有两个
外块。内部循环
但是当内部循环结束时,内部循环
其他块中的变量(除非内部循环未声明变量
同名)。例如,这将生成一个编译错误:
您将收到如下错误:
接下来的代码将编译
但是你会得到这个警告
在C99标准之前,您无法编写
在
仅在
以上。请注意,这仅适用于
从编译器。
也要注意分号,写
和做的一样
这是因为C语法基本上说,在
您需要一个语句或一个语句块。
什么都不做。
我认为这些很难发现错误,因为当您阅读时,大脑经常会错过
看线。
想改善这个问题吗? 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())
,if
,while
您需要一个语句或一个语句块。
for
是有效的声明什么都不做。
我认为这些很难发现错误,因为当您阅读时,大脑经常会错过
;
看线。
关于c - 使用声明的未声明的标识符“k”,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/48855288/