Benefits of using the conditional ?: (ternary) operator

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

    If you need multiple branches on the same condition, use an if:

    if (A == 6)
      f(1, 2, 3);
    else
      f(4, 5, 6);
    

    If you need multiple branches with different conditions, then if statement count would snowball, you'll want to use the ternary:

    f( (A == 6)? 1: 4, (B == 6)? 2: 5, (C == 6)? 3: 6 );
    

    Also, you can use the ternary operator in initialization.

    const int i = (A == 6)? 1 : 4;
    

    Doing that with if is very messy:

    int i_temp;
    if (A == 6)
       i_temp = 1;
    else
       i_temp = 4;
    const int i = i_temp;
    

    You can't put the initialization inside the if/else, because it changes the scope. But references and const variables can only be bound at initialization.

提交回复
热议问题