简体   繁体   中英

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

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

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.

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

在if语句之外声明长度。

length需要在顶部声明,因为它在if和outside的两个分支中使用(在return语句中)。

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM