Reputation: 3415
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
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
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
Reputation: 470
You declared the variable "length" inside first and second if statements. Thus, it is not visible outside if statements
Upvotes: 0
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
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