[英]use of undeclared identifier in 'c'
int get_cents(void)
{
do
{
int i = get_int("How many cents customer is owed?: ");
} while (i < 0);
return i;
}
我是初学者,我被困在这个问题上并收到错误 > 使用未声明的标识符
您必须检查 c 中的 scope 个变量。为简单起见,一个变量在{}
内可见,它已被声明,因此在您的情况下,变量i
不存在于循环之外。 您的代码的正确解决方案是:
int get_cents(void)
{
int i;
do
{
i = get_int("How many cents customer is owed?: ");
} while (i < 0);
return i;
}
在 C 中,变量有一个 scope。意味着变量有一个限制,直到它可以在哪里使用......任何变量的 scope 只是直到它被写入的复合体的右大括号。例如:
if(true){
int x = 999;
}
x++;
无法执行此操作,因为 x 是在if()
块的复合主体内声明的,因此它的使用限制仅在if()
块之前...即使您不放置大括号,该块仍然保持不变,因此您仍然会得到一个错误...这就是我的意思...
if(true)
int x = 999;
x++;
即使没有使用大括号{}
但此代码仍然会为您提供 output 因为x
在if()
块内声明并在其外部使用...
所以在你的程序中,只是你在do...while()
循环中声明变量i
所以它不能在do...while()
循环的条件下使用,因为它被认为是在do...while()
块。 所以这就是你应该写的......
int get_cents(void)
{
int i;
do
{
i = get_int("How many cents customer is owed?: ");
} while (i < 0);
return i;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.