C Ternary Operator (With Examples)
Overview
The C ternary operator, often represented as exp1 ? exp2 : exp3, is a valuable tool for making conditional decisions in C programming. This compact operator evaluates a condition and performs one of two expressions based on whether the condition is true or false. With its concise syntax and flexibility, the ternary operator is especially useful for streamlining conditional assignments.
Syntax
The syntax of the Ternary Operator in C is:
Syntax:
Working of Syntax :
- If the condition in the ternary operator is met (true), then the exp2 executes.
- If the condition is false, then the exp3 executes.
Example of C Ternary Operator
The following example explains the working of Ternary Operator in C.
so, if the condition 10 > 15 is true (which is false in this case) mxNumber is initialized with the value 10 otherwise with 15. As the condition is false so mxNumber will contain 15. This is how Ternary Operator in C works.
NOTE: Ternary operator in C, like if-else statements, can be nested.
Assign the Ternary Operator to a Variable:
You can assign the result of the ternary operator to a variable, as shown in the previous example with the variable max. This is a common use case for the ternary operator, where the result of the condition is stored in a variable for later use.
Example:
Ternary Operator Vs. if...else Statement in C:
The ternary operator and the if...else statement serve similar purposes but differ in syntax and use cases.
Example:
Attribute | Ternary | If-else |
---|---|---|
Syntax | Concise and compact | More verbose |
Use Cases | Suitable for simple conditions | Suitable for complex conditions |
Return Value | Returns a value | Doesn't return a value |
Error Handling | Limited in handling multiple conditions | Suitable for handling multiple conditions and cases |
Conclusion
- The C Ternary Operator is represented as exp1 ? exp2 : exp3, providing a concise way to make conditional decisions.
- If the condition exp1 is true, exp2 executes; otherwise, exp3 executes.
- It's useful for simple conditional assignments and can improve code readability in such cases.
- For more complex conditions, the if...else statement may be a better choice.
- Understanding the ternary operator enhances your ability to write concise and expressive C code for conditional operations.