Consider a scenario where you want to invert the sign of a numeric value only if a particular boolean condition is true. How can unary operators be utilized to achieve this without using an if statement?

  • int invertedValue = (condition) ? -numericValue : numericValue;
  • int invertedValue = (condition) ? numericValue : -numericValue;
  • int invertedValue = -numericValue;
  • int invertedValue = numericValue;
You can use the conditional (ternary) operator ? : to achieve this. If the condition is true, it negates the numericValue by using the unary minus operator. If false, it leaves the numericValue unchanged. Option 1 demonstrates this technique.
Add your answer
Loading...

Leave a comment

Your email address will not be published. Required fields are marked *