codescracker


c

C Ternary Operator



« Previous Tutorial Next Tutorial »


The ternary (?) operator is an alternative to if statement in certain condition.

You can use the ternary operator (?) to replace the if-else statement. Let's look at the following code fragment:

if(condition)
{
	var = expression;
}
else
{
	var = expression;
}

Now let's look at this code fragment:

Exp1 ? Exp2 : Exp3

here, Exp1, Exp2, and Exp3 are the expressions. First Exp1 is evaluated. If it is true, then Exp2 is evaluated and becomes the value of the entire expression. And if Exp1 is false, then Exp3 is evaluated and its value becomes the value of the entire expression. As you can see, both the code fragment is same. Now let's take a look at the following example which demonstrates the ternary operator.

C Ternary Operator Example

Following C code fragment shows the use of ternary operator:

x = 5;
y = x>4 ? 10 : 20;

In the above example, y is assigned the value 10. If x was less than 4, then y would have received the value 20. Following is the same code of the above, written with the if-else statement :

x = 5;
if(x>4)
{
	y = 10;
}
else
{
	y = 20;
}

« Previous Tutorial Next Tutorial »



Tools
Calculator

Quick Links
Signup - Login - Give Online Test