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

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

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.

  1. int power(int i) {
  2. int p = 1;
  3. for (int j = 1; j <= i; ++j) p = 2 * p;
  4. return p;
  5. }
  6. int lg(int N) {
  7. int i;
  8. for (i = 0; power(i) <= N; ++i) {}
  9. return i - 1;
  10. }
  11. int main() {
  12. power(2);
  13. printf("%d", lg(2));
  14. }
英文:

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.

  1. int power (int i) {
  2. int p = 1;
  3. for (int j = 1; j &lt;= i; ++j) p = 2 * p;
  4. return p;
  5. }
  6. int lg (int N) {
  7. for (int i = 0; power (i) &lt;= N; ++i) {}
  8. return i - 1;
  9. }
  10. int main () {
  11. power(2);
  12. printf(&quot;%d&quot;, lg(2));
  13. }

答案1

得分: 0

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

修复后的代码:

  1. int lg( int N ) {
  2. int i;
  3. for ( i = 0; power( i ) &lt;= N; ++i ) { }
  4. return i - 1;
  5. }

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

  1. int lg( int N ) {
  2. int i;
  3. int p = 1;
  4. for ( i = 0; p &lt;= N; ++i )
  5. p *= 2;
  6. return i - 1;
  7. }

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

  1. int lg( int N ) {
  2. int i;
  3. for ( i = 0; N &gt; 0; ++i )
  4. N /= 2;
  5. return i - 1;
  6. }
英文:

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:

  1. int lg( int N ) {
  2. int i;
  3. for ( i = 0; power( i ) &lt;= N; ++i ) { }
  4. return i - 1;
  5. }

As an aside, we can greatly reduce the number of multiplications:

  1. int lg( int N ) {
  2. int i;
  3. int p = 1;
  4. for ( i = 0; p &lt;= N; ++i )
  5. p *= 2;
  6. return i - 1;
  7. }

Instead of multiplying, we could divide.

  1. int lg( int N ) {
  2. int i;
  3. for ( i = 0; N &gt; 0; ++i )
  4. N /= 2;
  5. return i - 1;
  6. }

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:

确定