C++ Short Hand If Else
The short-hand if-else statement in C++ is known as the ternary operator. It provides a concise way to write conditional statements.
The syntax of the ternary operator is as follows:
condition ? expression1 : expression2
- The condition is evaluated first. If it is true, expression1 is executed; otherwise, expression2 is executed.
Here is an example that demonstrates the usage of the ternary operator:
int num = 10;
int result = (num > 5) ? num * 2 : num / 2;
Explanations for each step:
int num = 10;: In this step, we declare and initialize a variable
num
with the value 10.int result = (num > 5) ? num 2 : num / 2;: In this step, we use the ternary operator to assign a value to
result
based on the conditionnum > 5
. If the condition is true (which it is in this case),num 2
is assigned toresult
. Otherwise,num / 2
is assigned toresult
.
In this example, since num
is indeed greater than 5, num * 2
will be assigned to result
. Therefore, result
will have the value 20.
It's important to note that the ternary operator can only evaluate expressions, not statements. This means that the expressions expression1
and expression2
in the ternary operator can be simple calculations or function calls, but they cannot be complex statements or blocks of code.