Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IF-ELSE statement shortcut in C

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?

like image 463
sherrellbc Avatar asked Sep 05 '13 21:09

sherrellbc


People also ask

What is if else statement in short?

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).

What is if else statement in C?

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.

Is it else if or Elif in C?

' #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.

Does C use Elif?

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).


2 Answers

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.

like image 130
Jeremy Avatar answered Oct 23 '22 09:10

Jeremy


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)
like image 24
David M W Powers Avatar answered Oct 23 '22 08:10

David M W Powers