Search code examples
c++if-statementconditional-statementsstd-paircode-inspection

How can this if statement be simplified?


I am using CLion IDE to code my C++ project. Sometimes it happens that the IDE tries to be more intelligent than me and gives me suggestions. I have a simple problem during code inspection (by CLion). It says the following code can be simplified, even though I believe it is the most simple form I can think of :

Code :

    if (node.first >= 0 && node.first <= 45 &&
    node.second >= 0 && node.second <= 30)
    return true;
    else
    return false;

Assume node is of type std::pair<int, int>

The suggestion I get from the CLion IDE is the following:

Code Inspection comments :

Inspection info: This inspection finds the part of the code that can be simplified, e.g. constant conditions, identical if branches, pointless boolean expressions, etc.

Do you think this can be simplified more ?


Solution

  • CLion is hinting at you that this bit...

    if (node.first >= 0 && node.first <= 45 &&
        node.second >= 0 && node.second <= 30)
        return true;
    else
        return false;
    

    could just be re-written as

    return node.first  >= 0 && node.first  <= 45 &&
           node.second >= 0 && node.second <= 30;
    

    Since an expression used as a condition in a control statement obviously has a natural conversion to true and false.