Gustavo Rossatto
Gustavo Rossatto

Reputation: 3

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

Upvotes: 0

Views: 890

Answers (1)

ikegami
ikegami

Reputation: 385789

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;    
}

Upvotes: 0

Related Questions