看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 语法基本上说,在if、while、for 之后
您需要一个语句或一个语句块。 ; 是一个有效的声明
什么都不做。
在我看来,这些是很难找到的错误,因为当你阅读时大脑会经常错过;
看线。