Home > OS >  Is it possible to reduce an if_else statement to a single line code
Is it possible to reduce an if_else statement to a single line code

Time:08-12

I wonder if I can reduce the number of lines of the following code to a single one?

if (a > (b 10))
{
  value = 1;
}
else
{
  value = 0;
}

CodePudding user response:

For booleans (true, false) just do:

bool value = a > b   10;

CodePudding user response:

You could use the ternary operator:

value = (a > (b 10)) ? 1 : 0;

CodePudding user response:

For this case there are two options:

  • ternary operator
  • using the boolean value

Ternary operator

The ternary operator can substitute very simple if-else conditions such as:

value = (a > (b 10)) ? 1 : 0;

Boolean value

Since your condition is attributing the value of 1 or 0 you can simply use the condition evalution. In c when you evaluate a condition it returns an integer between 1 and 0. Which is exactly your objective, making the above expression even simpler.

value = (a > (b 10))

CodePudding user response:

Yes, using ternary operator.

Syntax:

var = (condition) ? (statements if condition is true) : (statements if condition is false);

Your example:

value = (a > (b 10)) ? 1 : 0;
  • Related