Benefits of using the conditional ?: (ternary) operator

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

    I usually choose a ternary operator when I'd have a lot of duplicate code otherwise.

    if (a > 0)
        answer = compute(a, b, c, d, e);
    else
        answer = compute(-a, b, c, d, e);
    

    With a ternary operator, this could be accomplished with the following.

    answer = compute(a > 0 ? a : -a, b, c, d, e); 
    

提交回复
热议问题