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;
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.
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.
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.
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.
foo =
(bar == 42) ? answerToEverything :
(bar == 23) ? bigMike :
useless;
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With