开发者

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 declar开发者_JAVA百科ed 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;
}


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.


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


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


Declare length outside of the if statements.


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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜