Complex if statement using ?: Operator in C

Is it possible to write the equivalent expression "if" using "?" operator in C? I want to write the expression "if-else if-else" and it was interesting, can I use "?" Operator.

I find the regular syntax to use is "?" will be something like

foo = (bar == 42) ? answerToEverything : useless;

If I wanted to rewrite the next statement on the same line using "?" operator, can i do this? How?

if(bar == 42) {
  foo = answerToEverything;
} 
else if(bar == 23) {
  foo = bigMike;
} 
else foo = useless;
+4
source share
8 answers
foo = 
    (bar == 42) ? answerToEverything :
    (bar == 23) ? bigMike :
    useless;
+12
source

Yes you can, but it's ugly and hard to understand!

, :

if (bar == 42) {
  foo = answerToEverything;
} else if (bar == 23) {
  foo = bigMike;
} else {
  foo = useless;
}

, , :

foo = (bar == 42)
  ? answerToEverything
  : (bar == 23)
      ? bigMike
      : useless;

, .

+5

, , .

, . .

foo = (bar == 42) 
  ? answerToEverything
  : ((bar==23) ? bigMike : useless );
+3

, (). (, () ?:, () ==. , .) , , ,

foo = 
  bar == 42 ? answerToEverything :
  bar == 23 ? bigMike :
  useless;

[] ?: , , . ( ) . (, , .) if-ladder , .

+2

. :

foo = (bar == 42) ? answerToEverything : ( (bar==23) ? bigMike : useless);

, , , if , , switch-case:

switch (bar) {
    case 42: foo = answerToEverything; break;
    case 23: foo = bigMike; break;
    default: foo = useless;
}
+1

?: .

, :

(bar == 42) ? (foo = answerToEverything): ((bar == 23) ? (foo = bigMike) : (foo = useless));
0

, ,

foo = (bar == 42) ? answerToEverything : ((bar == 23) ? bigMike : useless);

: - .

0

, , . , , if. , false.

foo = (bar == 42) ? "answerToEverything" : ((bar == 23) ? "bigMike" : "useless");

- foo int, , .

0

All Articles