A ternary operator operates on three operands, earning it the alias of conditional operator. The functionality of the conditional operator mirrors that of the 'if-else' statement, which is classified as a decision-making statement.
Syntax
It has the following syntax:
Expression1? expression2: expression3;
In this syntax,
- Expression1: An expression in logic that evaluates as non-zero if it is true and as zero if it is false.
- expression2: When the condition is true, the expression is evaluated, and its value is returned.
- expression3: The expression is checked, and its result is given if the condition is not true. The expression3 is said to be false only when it returns zero value.
C Conditional Operator Example
Let's consider an example to demonstrate the conditional operator in the C programming language.
Example
#include <stdio.h>
int main() //main function
{
int age; // variable declaration
printf("Enter your age: ");
scanf("%d",&age); // taking user input for age variable
(age>=18)? (printf("eligible for voting")) : (printf("not eligible for voting")); // conditional operator
return 0;
}
Output:
Enter your age: 12
not eligible for voting
Enter your age: 24
eligible for voting
Explanation:
In the provided code snippet, we are receiving the user's 'age' as input. Following that, we have implemented a condition utilizing a ternary operator. Within this condition, we are evaluating the user's age. If the user's age is 18 or older, statement1 will be executed, displaying "eligible for voting" using printf; otherwise, statement2 will be executed, displaying "not eligible for voting" using printf.
When should we use the Conditional Operator in C?
There are several situations where the condition operator can be used in C. Some main situations are as follows:
- When the condition and result expressions are simple and clear.
- When we want to decide to return or assign a value conditionally.
- When we need clear code for simple decisions.
There are several situations where the conditional operator can be avoided in C. Some main situations are as follows:
- When the expressions are complicated and involve more than one statement or result.
- When its purpose is to execute several operations, not only to evaluate just a value.
- When Readability is more important than how compact our code is.
Another Conditional Operator Example
Let's consider a different scenario to demonstrate the conditional operator in C programming.
Example
#include <stdio.h>
int main() //main function
{
int a=5,b; // variable declaration
b=((a==5)?(3):(2)); // conditional operator
printf("The value of 'b' variable is : %d",b);
return 0;
}
Output:
The value of 'b' variable is : 3
Explanation:
In this instance, we've defined a pair of variables, specifically 'a' and 'b', and allocated values to the 'a' variable. Following the declaration, we assign a value to the 'b' variable utilizing the ternary operator. When the 'a' value equals 5, 'b' is set to three; otherwise, it's assigned a value of 2.
Using the Ternary Operator in Functions and Expressions in C
There are multiple functions and expressions in C programming where the ternary operator can be applied. A few examples are listed below:
1) Using Ternary Operator Inside a Function for Return
In C programming, the ternary operator can be employed within a function's return statement to streamline logic flow.
Example
#include <stdio.h>
int max(int a, int b) {
return (a > b)? a: b;
}
int main() { //main function
int result = max(15, 27);
printf("Maximum is: %d\n", result);
return 0;
}
Output:
Maximum is: 27
2) Conditional Assignment
In the C programming language, the ternary operator can be employed for conditional assignment within the checkResult statement of a function, streamlining the logic.
Example
#include <stdio.h>
void checkResult(int marks) {
char *result = (marks >= 50) ? "Pass": "Fail";
printf("Result: %s\n", result);
}
int main() { //main function
checkResult(45);
checkResult(78);
return 0;
}
Output:
Result: Fail
Result: Pass
Explanation:
Within the function, a string is assigned based on the grades using the ternary operator, followed by displaying the result.
3) Ternary Inside printf
In C programming, we have the option to utilize the ternary operator within the printf function in order to showcase whether a number is even or odd.
Example
#include <stdio.h>
void printOddEven(int num) {
printf("%d is %s\n", num, (num % 2 == 0) ? "Even": "Odd");
}
int main() { //main function
printOddEven(7);
printOddEven(12);
return 0;
}
Output:
7 is Odd
12 is Even
Explanation:
In this instance, the ternary operator is directly employed within the printf function to display a message based on a value.
4) Nested Ternary Operator in Function Expression
In C programming, we have the option to employ the nested ternary operator within a function expression. Let's consider an instance where we assign grades according to the marks obtained.
Example
#include <stdio.h>
char getGrade(int marks) {
return (marks >= 90)? 'A' :
(marks >= 80) ? 'B' :
(marks >= 70) ? 'C' :
(marks >= 60) ? 'D': 'F';
}
int main() { //main function
int score = 75;
printf("Grade: %c\n", getGrade(score));
return 0;
}
Output:
Grade: C
Explanation:
In this instance, nested ternary operators are beneficial for efficiently choosing a grade character. This approach remains concise especially when the logic is not extensively nested.
5) Ternary Operator to Return Pointers in Function
In C programming, the ternary operator is also employed for returning pointers within functions. Let's consider an example to demonstrate how to return the memory address of the larger value using the ternary operator.
Example
#include <stdio.h>
int* maxPtr(int *x, int *y) {
return (*x > *y) ? x : y;
}
int main() { //main function
int a = 30, b = 40;
int *ptr = maxPtr(&a, &b);
printf("Greater value is: %d\n", *ptr);
return 0;
}
Output:
Greater value is: 40
Explanation:
In this instance, a ternary operator is employed to yield either of two pointers depending on the values they reference.
Difference between if-else and conditional operator in C
As is commonly understood, the functionality of the conditional operator and the 'if-else' statement is analogous, although they do exhibit certain distinctions.
| Aspect | if-else Statement | Conditional Operator (?:) |
|---|---|---|
| Syntax Type | Statement-based | Expression-based |
| Number of Operands | Works with one condition | Works with three operands (condition, true, false) |
| Value Return | Does not return a value; controls flow | Returns a value that can be assigned or returned |
| Code Length | Requires more lines and keywords | Condenses logic into a single-line |
| Use in Assignment | Needs extra steps for assignment | Directly assigns values based on condition |
| Readability | Better for multi-step or nested logic | Better for short, clear decisions |
| Expression Limitation | It can contain multiple complex statements | Limited to a single expression per branch |
| Performance | Same as the conditional operator (depends on the compiler) | Same as if-else; no performance benefit or loss |
| Nesting Support | Supports nested conditions cleanly | Supports nesting but becomes hard to read |
| Ideal Use Case | Complex branching, loops, multi-line blocks | Simple decisions like max = (a > b) ? a : b; |
C Example using if-else and Conditional Operator
Let's consider a scenario to demonstrate the use of if-else statements and the conditional operator in the C programming language.
Example
#include <stdio.h>
int main() { //main function
int a, b, max_ifelse, max_ternary;
// Input from user
printf("Enter two integers: ");
scanf("%d %d", &a, &b);
// Using if-else
if (a > b) {
max_ifelse = a;
} else {
max_ifelse = b;
}
// Using ternary (conditional) operator
max_ternary = (a > b) ? a: b;
// Output results
printf("\nUsing if-else: Maximum = %d\n", max_ifelse);
printf("Using ternary operator: Maximum = %d\n", max_ternary);
return 0;
}
Output:
Enter two integers: 25 42
Using if-else: Maximum = 42
Using ternary operator: Maximum = 42
Explanation:
In this instance, we are provided with a pair of integer values for comparison to determine the larger value. This process involves utilizing an if-else statement and a ternary operator to identify the maximum number. The if-else statement evaluates the two integers and assigns the larger value to max_ifelse variable, whereas the ternary operator accomplishes the same task in a concise, single-line format.
Conclusion
In summary, the ternary operator (?:) in the C programming language provides a straightforward method to assess conditions and provide outcomes without the need for traditional if-else statements. This operator, being expression-oriented, enables quick inline choices, particularly useful for assignments, function returns, and concise output messages.