Benefits of using the conditional ?: (ternary) operator

后端 未结 17 1029
孤街浪徒
孤街浪徒 2020-11-22 06:55

What are the benefits and drawbacks of the ?: operator as opposed to the standard if-else statement. The obvious ones being:

Conditional ?: Operator

17条回答
  •  再見小時候
    2020-11-22 07:36

    The scenario I most find myself using it is for defaulting values and especially in returns

    return someIndex < maxIndex ? someIndex : maxIndex;
    

    Those are really the only places I find it nice, but for them I do.

    Though if you're looking for a boolean this might sometimes look like an appropriate thing to do:

    bool hey = whatever < whatever_else ? true : false;
    

    Because it's so easy to read and understand, but that idea should always be tossed for the more obvious:

    bool hey = (whatever < whatever_else);
    

提交回复
热议问题