Solving a boolean equation with a recursive function

330 views Asked by At

I'm trying to code a function that takes a boolean equation as its input, and gives the answer of the equation as its output. For example:

Input: T & F | F

Output: F

However when I code it, there's this error that appears: "Non-void function does not return a value in all control paths" in my boolFunc function.

#include <iostream>
#include <cstring>
using namespace std;

bool boolFunc(char* input, long len){
    if(len == 1){
        if(*input == 'T')
            return true;
        else
            return false;
    }
    
    else{
        for (int i = 0; i < len; i++) {
            if(*(input + i) == '&'){
                return boolFunc(input, i) && boolFunc(input+i+1, len-i);
            }
            if(*(input + i) == '|'){
                return boolFunc(input, i) || boolFunc(input+i+1, len-i);
            }
        }
    }
}


int main(){
    char input[500] = {'\0'};
    cin.getline(input, 500);
    
    if(boolFunc(input,strlen(input)))
        cout << "T";
    else
        cout << "F";
    
    return 0;
}

1

There are 1 answers

3
Heng Wei On

I fixed the error, although there might be another logic error, in the case T|F&F, the order of operations must follow the right order (left to right)

bool boolFunc(char* input, long len){
    if(len == 1){
        if(*input == 'T')
            return true;
        else
            return false;
    }
    
    else{
        for (int i = 0; i < len; i++) {
            if(*(input + i) == '&'){
                return boolFunc(input, i) && boolFunc(input+i+1, len-i);
            }
            if(*(input + i) == '|'){
                return boolFunc(input, i) || boolFunc(input+i+1, len-i);
            }
        }
    }
    //CORRECTION 
    return false;
}