Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compound if statement using ?: operator in C [duplicate]

Is it possible to write the equivalent compound "if" statement using the "?" operator in C? I want to write an "if - else if - else" statement and was wonder if I could utilize the "?" operator.

I believe the regular syntax for using "?" would be something like

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

If I wanted to rewrite the following statement in one line using the "?" operator, could I do that? How?

if(bar == 42) {
  foo = answerToEverything;
} 
else if(bar == 23) {
  foo = bigMike;
} 
else foo = useless;
like image 448
23ChrisChen Avatar asked Jul 31 '14 16:07

23ChrisChen


People also ask

Can IF statement have 2 conditions in C?

Nested if statements mean an if statement inside another if statement. Yes, both C and C++ allow us to nested if statements within if statements, i.e, we can place an if statement inside another if statement.

How do you write multiple conditions in a single IF statement?

Here we'll study how can we check multiple conditions in a single if statement. This can be done by using 'and' or 'or' or BOTH in a single statement. and comparison = for this to work normally both conditions provided with should be true. If the first condition falls false, the compiler doesn't check the second one.

Can we use if statement twice?

Answer 514a8bea4a9e0e2522000cf1You can use multiple else if but each of them must have opening and closing curly braces {} . You can replace if with switch statement which is simpler but only for comparing same variable.

What is #if in C?

Description. In the C Programming Language, the #if directive allows for conditional compilation. The preprocessor evaluates an expression provided with the #if directive to determine if the subsequent code should be included in the compilation process.


2 Answers

foo = 
    (bar == 42) ? answerToEverything :
    (bar == 23) ? bigMike :
    useless;
like image 151
Bill Lynch Avatar answered Nov 15 '22 02:11

Bill Lynch


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

I would advise using the multiline form, since it's easier to comprehend:

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

But, if you really want to make your code difficult to read:

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

Of course, feel free to format with whitespace as you see fit.

like image 31
maerics Avatar answered Nov 15 '22 02:11

maerics