Page 38 - DCAP404 _Object Oriented Programming
P. 38
Unit 2: Beginning of OOP Language
|| Evaluate to true, a>6 || y < 20 The result is true if either Notes
if at least one of the condition1 (a>6) and
conditions evaluates to condition2 (y<20) or both
true and false if none evaluate to true. If both
of the conditions the conditions are false,
evaluate to true. the result is false.
Short Circuit Logical Operators
These operators (&&, ||) appear to be similar to the bit-wise & and | operators, except that they are
limited to Boolean expressions only. However, the difference lies in the way these operators work.
In the bit-wise operators, both the expressions are evaluated. This is not always necessary since:
false & a would always result in false
true | a would always result in true
Short circuit operators do not evaluate the second expression if the result can be obtained by
evaluating the first expression alone.
For example
a < 6 && y > 20
The second condition (b>20) is skipped if the first condition is false, since the entire expression
will anyway, be false. Similarly with the || operator, if the first condition evaluates to true, the
second condition is skipped as the result, will anyway, be true. These operators, && and ||, are
therefore, called short circuit operators.
Notes If you want both the conditions to be evaluated irrespective of the result of the first
condition, then you need to use bit-wise operators.
2.3.8 Conditional Operators
Operator Description Example Explanation
(condition) Evaluates to va11 if a = (b>c) ? b:c A is assigned the value in
va11, va12 the condition returns b, if b is greater than c,
true and va12 if the else a is assigned the
condition returns false value of c.
This example finds the maximum of two given numbers.
If (num1 > num2)
{
imax = num1;
}
else
{
imax = num2;
}
LOVELY PROFESSIONAL UNIVERSITY 31