- C Programming
- C Tutorial
- C Basic Syntax
- C Data Types
- C if...else Statement
- C switch Statement
- C for Loop
- C while Loop
- C do...while Loop
- C Jump Statements
- C Arrays
- C Strings
- C Pointers
- C Functions
- C Recursion
- C Variable Scope
- C Structures
- C Linked Lists
- C Stacks
- C Queues
- C Binary Trees
- C Header Files
- C File I/O
- C Programming Examples
- C Programming Examples
- Computer Programming
- C++ Tutorial
- C++ Examples
- C# Tutorial
- Python Tutorial
- Python Keywords
- Python Built-in Functions
- Python Examples
- Java Tutorial
- Java Examples
- PHP Tutorial
- Web Development
- HTML Tutorial
- CSS Tutorial
- JavaScript Tutorial
- SQL Tutorial
C Ternary Operator
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 »
Follow/Like Us on Facebook
Subscribe Us on YouTube