C - Conditional Operator

Learn C - C tutorial - C conditional operator - C examples - C programs
C Conditional Operator - Definition and Usage
- In C-programming the conditional operator return one value if condition is true and returns another value if condition is false.
- Conditional operators is also called as ternary operator.

C Syntax
(Condition? true_value: false_value);
Sample - C Code
#include <stdio.h>
#include <conio.h>
void main()
{
int x=1, y ;
y = ( x ==1 ? 2 : 0 ) ;
printf("x value is %d\n", x);
printf("y value is %d", y);
getch();
}
C Code - Explanation

- In this statement we declare the variable “x=1” and y as integer.
- In this statement we check the condition using ternary operator that is if “x==1” means it sets “true” ,so the value for “y” is “2” otherwise it sets the “y” value as “0”.
- Here we print the value of “x” using the printf statement.
- Here we print the value of “y” using the printf statement.
Sample Output - Programming Examples

- Here we printed the value of “x” as “1”.
- Here in this output the conditional operation has been performed and the condition has been satisfied so the value of the “Y” variable will be printed as “2”.