c++nested-if

What is a simpler/more readable alternative to this code structure?


There been many times lately where a C++ exercise has required me to do perform operations dependent on the relation between elements in a vector. For example to do x only if the next element in the vector is greater than the previous and do y otherwise.

I often solve these problems with the general code structure:

void foo()
{
    std::vector<int> v;
    for (size_t i = 0; i < v.size(); ++i)
    {
        if (i < v.size() - 1)
        {
            if (v[i + 1] > v[i])    // some sort of condition
            {
                // execute compound statement x
            }
            else 
            {
                // execute compound statement y
            }
        }
        else 
        {
            // execute compound statement y
        }
    }
}

But it often becomes messy and hard to read when the compound statements x and y become large. Partially because I often have to create a function containing compound statement y to prevent having to copy all its code twice.
What is a more readable alternative to this structure?


Solution

  • In this specific case you can simply use:

    if ((i < v.size() - 1) && (v[i + 1] > v[i]))
    {
         // execute compound statement x
    }
    else 
    {
         // execute compound statement y
    }
    

    Note that thanks to the feature of Short-circuit evaluation in C++ (as well as other languages), it is guaranteed that (v[i + 1] > v[i]) will not be evaluated if (i < v.size() - 1) is false, and therefore there is no risk of accessing the vector out of bounds.

    Also note that this would work for an empty vector as well (and there is no problem with evaluating (i < v.size() - 1)), because in this case the for loop (where this if resides) will not even iterate once.