error ‘symbol’ undeclared (first use in this function)

huangapple go评论62阅读模式
英文:

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 &lt;= i; ++j) p = 2 * p;
    return p;
}
int lg (int N) {
    for (int i = 0; power (i) &lt;= N; ++i) {}
    return i - 1;    
}
int main () {
    power(2);
    printf(&quot;%d&quot;, lg(2));
}

答案1

得分: 0

for循环的第一个表达式中声明的变量的作用域限定在该语句内。它们仅在该语句的范围内存在(包括循环体)。

修复后的代码:

int lg( int N ) {
    int i;
    for ( i = 0; power( i ) &lt;= N; ++i ) { }
    return i - 1;    
}

另外,我们可以大大减少乘法的次数:

int lg( int N ) {
    int i;
    int p = 1;
    for ( i = 0; p &lt;= N; ++i )
       p *= 2;

    return i - 1;    
}

除了乘法,我们也可以使用除法:

int lg( int N ) {
    int i;
    for ( i = 0; N &gt; 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 ) &lt;= 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 &lt;= N; ++i )
       p *= 2;

    return i - 1;    
}

Instead of multiplying, we could divide.

int lg( int N ) {
    int i;
    for ( i = 0; N &gt; 0; ++i )
       N /= 2;

    return i - 1;    
}

huangapple
  • 本文由 发表于 2023年6月15日 18:45:05
  • 转载请务必保留本文链接:https://go.coder-hub.com/76481717.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定