Multiple Ternary operator in c++

mdv picture mdv · Sep 26, 2013 · Viewed 9.6k times · Source

I have a doubt in the following scenario (C++):

Say, I have an if condition

if ( a ? b ? c : d : false)
{
    // do something
}
else
{
    // do something else
}

This is my interpretation of how it works:

If a is true, it checks b. Then,
    - If b is true, the if loop is reduced to if (c)
    - If b is false, the if loop is reduced to if (d)
If a is false, the if loop is reduced to if (false)

Is my understanding correct?
Is using this better or multiple if/else checks?

Answer

Manikandan Sigamani picture Manikandan Sigamani · Sep 26, 2013

Please use this in parenthesis, as it helps improve readability. Also, it is fine using multiple ternary operators.

if ( a ? (b ? c : d) : false)
{
    // do something
}
else
{
    // do something else
}