c++syntaxboolean

Is there a more elegant syntax for these boolean expressions?


I was just writing an improved linear version of a recursive Fibonacci algorithm, and realized that my boolean expressions look really bad and unreadable. Is there a cleaner way to do what I'm trying to do?

int fibonacci(int num) {

    if (num <= 1)
        return num;

    // starts looking ugly here

    int a = intExists(num-1);
    int b = intExists(num-2);

    bool aAndB = (a != -1 && b != -1);
    bool justA = (a != -1 && b == -1);
    bool justB = (a == -1 && b != -1);

    int number = 0;

    if (aAndB)
        number = (a + b);
    else if (justA)
        number = (a + fibonacci(num - 2));
    else if (justB)
        number = (fibonacci(num-1) + b);
    else
        number = (fibonacci(num - 1) + fibonacci(num - 2));

    map.push_back(Pair(num, number));

    return number;
}

Thanks


Solution

  • If you're talking about:

    bool aAndB = (a != -1 && b != -1);
    

    then I would say, "no."

    This code looks perfectly expressive to me. aAndB is initialized at the moment it comes in to being, and the conditions are very clear. This might look a bit odd when you're first starting out in C++, but before you know it it will be second nature and other constructs will seem silly.

    One thing I would suggest is to make aAndB const if you don't intend to change it:

    const bool aAndB = (a != -1 && b != -1);
    

    This is even more expressive.

    It also might give the compiler an additional opportunity to optimize your code.

    Remember -- write code for humans to understand. Not for computers to understand.