Multiple conditions in the ternary operator safe?

前端 未结 6 1526
情话喂你
情话喂你 2021-01-17 09:22

I have seen advice that says the ternary operator must not be nested.

I have tested the code below and it works okay. My question is, I haven\'t seen the ternary op

6条回答
  •  爱一瞬间的悲伤
    2021-01-17 10:08

    It's legal and doesn't have to be "ugly". I use the "hook" operator often, in table form it's quite clean, e.g.:

    bool haveANeed() 
    { 
        //     Condition       result
        //     ----------      ------
        return needToEat()   ? true
             : needToSleep() ? true
             : needToStudy() ? true
             : needToShop()  ? true
             : needToThink() ? true
             :                 false; // no needs!
    }
    

    This function would, IMHO, be less clear and certainly longer if written with if-else logic.

提交回复
热议问题