1
Ternary / Conditional operator( ? : )
It is similar to if else / ladder if in working
style.
It allows to complete if else / ladder if in a
single statement.
When we are working with if else/ladder if
it is going to take more than one line of
statements. Ternary operator is going to
finish the same task in a single statement.
But the difference between if …else and
ternary operator is ternary operator
supports only one statement at a time and
if supports any number of statements.
It is having 3 expressions. Hence it is called
ternary operator.
2
It is starting with a condition. Hence it is
called conditional operator.
Syntax:
condition ? true statement : false statement ;
exp1/op1 exp2/op2 exp3/op3
If condition true, statement after ?
executed.
If condition false, statement after : is
executed.
When compared with if else, conditional
operator performance is high.
3
Eg:Finding big in two no’s using ternary
operator.
4
5
6
7
8
9
10
SWITCH
It is a selection statement.
It is used to execute one case of statements from no
of cases according to the switch expression value
matched with case expression value. In switch the
program is jumped to matching case like the go to
label.
It is similar to ladder if in working style.
Switch performance is high when compared with
ladder if because of it jumps to matching case.
11
Syntax:
switch(expression)
{
case constexp1:
statements;
break;
case constexp2:
statements;
break;
case constexpN:
statements;
break;
[ default: statements; ]
}
Here switch, case, break, default are the keywords.
In between case and case expression / value at least
one space should be provided. Otherwise it will
become a label.
12
case expression should be a constant integer/char
value. i.e. float / string not allowed.
One case contains one expression only.
case expression doesn’t contain any separators
like , . etc.
case expression should be end with : (colon)
Each case should be separated with break keyword.
Otherwise remaining cases also executed.
Duplicate cases not allowed.
default is similar to the else and all cases are failed
then default statements are executed. Default is
optional and we can declare it anywhere in our
switch.
Outside case expressions not considered in switch.