Home > front end >  Non-void function does not return a value in all control paths in recursive function in C
Non-void function does not return a value in all control paths in recursive function in C

Time:03-19

I am trying to make a recursive function where I am returned true if a string includes a comma. However, I am getting the following error: Non-void function does not return a value in all control paths

This is my code:

bool hasComma(string sentence, int index) {
    if (index == -1)
        return false;
    else if (sentence[index] == ',')
        return true;
    else
        hasComma(sentence, index - 1);
        
}

int main() {
    string sentence = "Hello, world.";
    if (hasComma(sentence, int(sentence.size() - 1)))
       cout << "Sentence has a comma." << endl;
    
    return 0;
}

Any help would be appreciated.

CodePudding user response:

This:

else
    hasComma(sentence, index - 1);

Should be:

else
    return hasComma(sentence, index - 1);

Otherwise, what are you returning? That's what the compiler is warning you about.

CodePudding user response:

At the point you're making the recursive call, you're not returning anything. You want to return the result of that call.

bool hasComma(string sentence, int index) {
    if (index == -1)
        return false;
    else if (sentence[index] == ',')
        return true;
    else
        return hasComma(sentence, index - 1);
}
  • Related