tags:

views:

265

answers:

6

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;
}
+1  A: 

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

ennuikiller
+1  A: 

Declare length outside of the if statements.

Jonathan
+1  A: 
Jeff Foster
+4  A: 

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;
}
Jon Skeet
@metashockwave: Yes, it is.
SLaks
A: 

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

vasin
+2  A: 

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.

Andomar