How to rewrite complicated lines of C++ code (nested ternary operator)

后端 未结 7 1575
误落风尘
误落风尘 2020-12-05 23:29

I\'ve been looking through someone else\'s code for debugging purposes and found this:

!m_seedsfilter ? good=true : m_seedsfilter==1 ? good=newClusters(Sp) :         


        
7条回答
  •  抹茶落季
    2020-12-06 00:07

    To answer your main question, this is an example of a conditional expression:

    conditional-expression:
        logical-OR-expression
        logical-OR-expression ? expression : conditional-expression
    

    If the logical-OR-expression evaluates to true, then the result of the expression is the expression following the ?, otherwise it's the expression following the :. For example,

    x = y > 0 ? 1 : 0;
    

    will assign 1 to x if y is greater than 0, otherwise it will assign '0'.

    You're right to feel queasy about the example because it's badly written. The author is trying to use the ?: operator as a control structure, which it's not meant for.

    A better way to write this would be

    
        good = !m_seedsfilter ? true : 
                                ( m_seedsfilter == 1 ? newClusters(SP) : 
                                                       newSeed(SP) );
    

    If m_seedsfilter equals 0, then good will be set to true. If m_seedsfilter equals 1, then good will be set to the result of newClusters(SP). Otherwise, good will be set to the result of newSeed(SP).

提交回复
热议问题