Cconditional
Operators
Said Msihullah Hashimi, M.Sc. NTM
INTRODUCTION
○Theconditional operatoris the one operator in
C that is considered aternary operator,
specifically because it requires three operands.
○Binary operators require two operands, and
unary operators require one operand. So, the
conditional operator is not THE ternary
operator. It is an operator that just happens to
be ternary.
○The conditional operator is a shorthand for a
specific if-else control structure scenario.
2
Syntax
“
4
○The basic syntax of a Ternary Operator in C Programming is as
shown below:
expression ? statement1: statement2
○From the above syntax, If the given test condition is true then it
will return statement1 and if the condition is false then statement2
is returned.
Slide to see how it works.
5
Example
6
/* Ternary Operator in C Example */
#include<stdio.h>
intmain()
{
intage;
printf(" Please Enter your age here: \n ");
scanf(" %d ", &age);
(age >= 18) ? printf(" You are eligible to Vote ") : printf(" You are not eligible to Vote ");
return 0;
}
Compare with if-else
7
char*diagnosis;
doubletemperature;
if(temperature <= 98.6)
{
diagnosis = "well";
}
else
{
diagnosis = "sick";
}
printf("With a temperature of %.1f,
you appear to be
%s.\n",temperature, diagnosis);
If-else and
Conditional
Code block
Comparison
char*diagnosis;
doubletemperature;
diagnosis = (temperature <= 98.6) ?
"well" : "sick";
printf("With a temperature of %.1f, you
appear to be %s.\n",
8
Points to
Remember
○The conditional operator does not take the place of all if-else control
structures. It is designed specifically for the situation where an
expression needs to take on one value if the condition is true, and a
different value of the condition is false.
○Some coding/style standards consider the conditional operator to be
less readable than the equivalent if-else statement, so check your local
coding/style standard.
○Although conditional operators can be nested (i.e., another conditional
operator can be used inside the true section between the ? and :,
another conditional operator can be used inside the false section after
the :), this practice leads much less readable code.
○Nesting of conditional operators should be avoided, to keep the code
readable and maintainable.
○You may find the conditional operator used in #define macros, because
it facilitates conditional decisions within an expression.
9