Conditional Operator
Conditional Operator
The behavior of the conditional operator is similar to the 'if-else' statement as 'if-else'
statement is also a decision-making statement.
o In the above syntax, the expression1 is a Boolean condition that can be either
true or false value.
o If the expression1 results into a true value, then the expression2 will execute.
o If the expression1 returns false value then the expression3 will execute.
In the above code, we are taking input as the 'age' of the user. After taking input, we
have applied the condition by using a conditional operator. In this condition, we are
checking the age of the user. If the age of the user is greater than or equal to 18, then
the statement1 will execute, i.e., (printf("eligible for voting")) otherwise, statement2
will execute, i.e., (printf("not eligible for voting")).
If we provide the age of user below 18, then the output would be:
If we provide the age of user above 18, then the output would be:
As we can observe from the above two outputs that if the condition is true, then the
statement1 is executed; otherwise, statement2 will be executed.
Till now, we have observed that how conditional operator checks the condition and
based on condition, it executes the statements. Now, we will see how a conditional
operator is used to assign the value to a variable.
1. #include <stdio.h>
2. int main()
3. {
4. int a=5,b; // variable declaration
5. b=((a==5)?(3):(2)); // conditional operator
6. printf("The value of 'b' variable is : %d",b);
7. return 0;
8. }
In the above code, we have declared two variables, i.e., 'a' and 'b', and assign 5 value
to the 'a' variable. After the declaration, we are assigning value to the 'b' variable by
using the conditional operator. If the value of 'a' is equal to 5 then 'b' is assigned with a
3 value otherwise 2.
Output
The above output shows that the value of 'b' variable is 3 because the value of 'a'
variable is equal to 5.
As we know that the behavior of conditional operator and 'if-else' is similar but they
have some differences. Let's look at their differences.
o A conditional operator can also be used for assigning a value to the variable,
whereas the 'if-else' statement cannot be used for the assignment purpose.
o It is not useful for executing the statements when the statements are multiple,
whereas the 'if-else' statement proves more suitable when executing multiple
statements.
o The nested ternary operator is more complex and cannot be easily debugged,
while the nested 'if-else' statement is easy to read and maintain.