Why would you choose to use the ternary operator (?:) over a "traditional" if..else block? [duplicate]

StackOverflow https://stackoverflow.com/questions/21803857

  •  12-10-2022
  •  | 
  •  

質問

The ternary operator in C (and many other languages), ?:, is a compressed if-then-else statement.

For example:

a > b ? func(a) : func(b) ;

Why/when would you use it over an if-then-else?

Is it functionally different from if...else - and, if so, how?

役に立ちましたか?

解決

As you say, is a compressed if-then-else, so it must be compiled to the same instructions with regards of the comparisons.

The real difference is that it selects a final result. Really, just syntactic sugar that improves readability.

Compare:

int val = (foobar == true) ? 500 : 1000 ;

vs:

int val = 0;
if (foobar == true) 
{
    val = 500;
} else {
    val = 1000;
}

It can be argued that it is just a matter of style, thus subjective. But, the legibility becomes even greater when you have a more complex decision tree, such as:

int val = (flag01 == true) ? 
              (flag02 == true ) ? 100 : 200 :
              (flag03 == true ) ? 300 : 400 ;

You can chain together many decisions in one place instead of writing a bunch of nested if-then-else clauses:

 int val = 0;
 if (flag01 == true) 
 {
     if (flag02 == true) 
     {
         val = 100; 
     } else {
         val = 200;
     }
 } else {
     if (flag03 == true) 
     {
        val = 300;
     } else {
        val = 400;
     }
 }

This is somewhat following a code pattern called method chaining.

他のヒント

As you already stated, the ternary operator works like a if-else-statement. its primary use is compressing your code and make it easier to read. Something like that:

int a;
if (b == c){
    a = 1;
}
else {
    a = 2;
}

can be converted to:

int a = (b == c ? 1: 2);

(parantheses are unneccessary here but they make the code look bettes)

The conditional operator can be faster than a traditional if-then-else block however be very careful when using it because if the code going into the conditional operator isn't stable then it can cause you to have problems without knowing where they are coming from.

You can also use the conditional operator to select which lvalue to assign a rvalue to.

(UseIntA == true)? IntA : IntB = SomeValue;

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top