user133466
user133466

Reputation: 3415

undeclared identifier error occurs when I already have declared the variable

I got an undeclared identifier error from the follow code, but i have clearly declared the variable "length" in both cases. what did I do wrong?

int startWordLenRec(char s[]) {
    if (isLetter(s) == false){
        int length = 0;
    }
    else if{
        int length = 1 + startWordLenRec(s+1);
    }
    return length;
}

Upvotes: 0

Views: 7815

Answers (6)

Jon Skeet
Jon Skeet

Reputation: 1500425

You've declared two variables in two different blocks, but then tried to use them outside of those blocks. Instead you want to declare one variable, and assign a value to it within each of the blocks:

int startWordLenRec(char s[]) {
    int length;
    if (isLetter(s) == false){
        length = 0;
    }
    else {
        length = 1 + startWordLenRec(s+1);
    }
    return length;
}

(I removed the extraneous "if" from after the "else".)

However, a conditional expression would be clearer (IMO):

int startWordLenRec(char s[]) {
    return isLetter(s) ? 1 + startWordLenRec(s+1) : 0;
}

Upvotes: 4

Andomar
Andomar

Reputation: 238076

A declaration is local to the scope you declare it in. So if you declare it inside {}, it cannot be used after the closing }.

int startWordLenRec(char s[]) {
    int length;
    if (isLetter(s) == false){
        length = 0;
    }
    else if{
        length = 1 + startWordLenRec(s+1);
    }
    return length;
}

Of course, you can also return 0; directly, without a separate variable.

Upvotes: 4

vasin
vasin

Reputation: 470

You declared the variable "length" inside first and second if statements. Thus, it is not visible outside if statements

Upvotes: 0

Jeff Foster
Jeff Foster

Reputation: 44706

length needs to be declared at the top, since it is used in both branches of the if and outside (in the return statement).

Upvotes: 1

Jonathan
Jonathan

Reputation: 1731

Declare length outside of the if statements.

Upvotes: 1

ennuikiller
ennuikiller

Reputation: 46965

Move the declaration of length outside of the if statement. The way your currently have it declared it ceases to exit after the if statement executes so return length is always undeclared

Upvotes: 1

Related Questions