Conditional Operator in C
C

Conditional Operator In C Language with Example (?:)

The conditional operators in C language are known by two more names

Ternary Operator
?: Operator

It is actually the if condition that we use in C language decision making, but using conditional operator, we turn the if condition statement into a short and simple operator.

The syntax of a conditional operator is :

expression 1 ? expression 2: expression 3

Explanation:

The question mark “?” in the syntax represents the if part.
The first expression (expression 1) generally returns either true or false, based on which it is decided whether (expression 2) will be executed or (expression 3)
If (expression 1) returns true then the expression on the left side of ” : ” i.e (expression 2) is executed.
If (expression 1) returns false then the expression on the right side of ” : ” i.e (expression 3) is executed.

Here are some Examples of Conditional Operator

Example 1, Program for Check the Properties of Pointers.

#include<stdio.h>
void main()
{
int salary;
int *pntr;
salary=3000;
pntr=&salary;
printf("\nThe value of salary is %d",salary); 
printf("\nThe value pointed to is %d",*pntr); 
*pntr=3333;
printf("\nThe value of salary is %d",salary); 
}

RUN
The Value of Salary is 3000
The Value of Pointed to is 3000
The Value of Salary if 3333

Example 2, Use of Conditional Operator (?:)

#include<stdio.h>
void main()
{
int a,b;
printf("\nEnter the value of the variable \"a\": ");
scanf("%d",&a);
b=a>25 ? 100 : 99;
printf("\nThe value of the variable \"b\" is %d",b);
}

RUN
Enter the value of the variable "a":6
The Value of the variable "b" is 99

Example 3,  The use of conditional expressions in which one statement falls within another

#include<stdio.h>
void main()
{
int a, b;
char *msg1, *msg2, *msg3;
msg1="The value of \"a\" is greater than 25";
msg2="The value of \"a\" is less than or equal to 25";
msg3="The value of \"b\" is: " ;
printf("\nEnter the value of the variable \"a\": ");
scanf("%d",&a);
printf("\n%s",a>25 ? msg1 : msg2);
printf("\n%s %d",msg3,b=a>25 ? 100 :99); 
}

RUN
Enter the value of the variable "a":77
The Value of "a" is greater than 25
The Value of "b" is: 100

 

 

 

 

 

 

 

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.