C has the following syntax for a shorthand IF-ELSE statement
(integer == 5) ? (TRUE) : (FALSE);
I often find myself requiring only one portion (TRUE or FALSE) of the statement and use this
(integer == 5) ? (TRUE) : (0);
I was just wondering if there was a way to not include the ELSE portion of the statement using this shorthand notation?
An if else statement in programming is a conditional statement that runs a different set of statements depending on whether an expression is true or false. A typical if else statement would appear similar to the one below (this example is JavaScript, and would be very similar in other C-style languages).
In C programming language, if-else statement is used to perform the operations based on some specific condition. If the given condition is true, then the code inside the if block is executed, otherwise else block code is executed. It specifies an order in which the statements are to be executed.
' #elif ' stands for “else if”. Like ' #else ', it goes in the middle of a conditional group and subdivides it; it does not require a matching ' #endif ' of its own. Like ' #if ', the ' #elif ' directive includes an expression to be tested.
The elif preprocessor directive in C is equivalent to an else if statement – it provides an alternate path of action when used with #if , #ifdef , or #ifndef directives. Execution enters the #elif block when the #if condition is false and the elif condition holds true (this is shown below).
The operator ?:
must return a value. If you didn't have the "else" part, what would it return when the boolean expression is false? A sensible default in some other languages may be null, but probably not for C. If you just need to do the "if" and you don't need it to return a value, then typing if
is a lot easier.
Question is whether we can somehow write the following expression without both then and else parts
(integer == 5) ? (THENEXPR) : (ELSEEXPR);
If you only need the then part you can use &&:
(integer == 5) && (THENEXPR)
If you only need the else part use ||:
(integer == 5) || (ELSEEXPR)
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