
Ternary Operator in C
The ternary operator in C, often referred to as the conditional operator, provides a shorthand method for performing conditional assignments or evaluations.
condition ? expression1 : expression2;
condition : A boolean expression that evaluates to either true or false.
expression1 : The result if the condition is true.
expression2 : The result if the condition is false.
The ternary operator evaluates the condition:
- If the condition is true, expression1 is executed and its value is returned.
- If the condition is false, expression2 is executed and its value is returned.
Output :
The maximum is 20
Explanation :
- The condition (a > b) checks if a is greater than b.
- If true, max is assigned the value of a.
- If false, max is assigned the value of b.
Output :
7 is odd
Output :
Enter your age: 20
Allowed
Output :
Enter year:2004
Leap-Year
The ternary operator is a powerful tool in C programming that, when used appropriately, can lead to cleaner, more concise, and potentially more efficient code. It is particularly beneficial for simple conditional assignments and expressions, allowing developers to write more expressive and compact code. However, judicious use is essential to maintain code readability and clarity.