英文:
error 'symbol' undeclared (first use in this function)
问题
My question is: Why the compiler doesn't run my code if the symbol is declared?
I'm trying to run this code on Ubuntu Linux with gcc. But when I try to run it, it says "'i' not declared (first use in this function) return i - 1;". I googled several questions about it.
I'm starting with programming and C language, and this code is not mine; it serves to calculate the greatest power of 2 that does not exceed N.
int power(int i) {
int p = 1;
for (int j = 1; j <= i; ++j) p = 2 * p;
return p;
}
int lg(int N) {
int i;
for (i = 0; power(i) <= N; ++i) {}
return i - 1;
}
int main() {
power(2);
printf("%d", lg(2));
}
英文:
My question is: Why the compiler doesn't run my code if the symbol is declared?
I'm trying to run this code on Ubuntu Linux with gcc. But when I try to run it, it says "'i' not declared (first use in this function) return i - 1;". I googled several questions about it.
I'm starting with programming and C language and this code is not mine, it serves to calculate the greatest power of 2 that does not exceed N.
int power (int i) {
int p = 1;
for (int j = 1; j <= i; ++j) p = 2 * p;
return p;
}
int lg (int N) {
for (int i = 0; power (i) <= N; ++i) {}
return i - 1;
}
int main () {
power(2);
printf("%d", lg(2));
}
答案1
得分: 0
在for
循环的第一个表达式中声明的变量的作用域限定在该语句内。它们仅在该语句的范围内存在(包括循环体)。
修复后的代码:
int lg( int N ) {
int i;
for ( i = 0; power( i ) <= N; ++i ) { }
return i - 1;
}
另外,我们可以大大减少乘法的次数:
int lg( int N ) {
int i;
int p = 1;
for ( i = 0; p <= N; ++i )
p *= 2;
return i - 1;
}
除了乘法,我们也可以使用除法:
int lg( int N ) {
int i;
for ( i = 0; N > 0; ++i )
N /= 2;
return i - 1;
}
英文:
Variables declared in a the first expression of a for
loop are scoped to the statement. They only exist for the span of the statement (including the body of the loop).
Fixed:
int lg( int N ) {
int i;
for ( i = 0; power( i ) <= N; ++i ) { }
return i - 1;
}
As an aside, we can greatly reduce the number of multiplications:
int lg( int N ) {
int i;
int p = 1;
for ( i = 0; p <= N; ++i )
p *= 2;
return i - 1;
}
Instead of multiplying, we could divide.
int lg( int N ) {
int i;
for ( i = 0; N > 0; ++i )
N /= 2;
return i - 1;
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论