Benefits of using the conditional ?: (ternary) operator

后端 未结 17 1295
孤街浪徒
孤街浪徒 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:38

    I would basically recommend using it only when the resulting statement is extremely short and represents a significant increase in conciseness over the if/else equivalent without sacrificing readability.

    Good example:

    int result = Check() ? 1 : 0;
    

    Bad example:

    int result = FirstCheck() ? 1 : SecondCheck() ? 1 : ThirdCheck() ? 1 : 0;
    

提交回复
热议问题