LT4 Control Flow - Conditional Statements
Syntax Summary
- Keywords
- if, else
- switch, case, default
- break, continue
- Punctuators
- (), {},
- :
- ? :
- Operators
- ==, !, !=, >, >=, <, <=, &&, ||
Logical expression
0 is false, false is 0
- Any value other than 0 / false deems to be true in logic expression. (&&0=0)
- However, true = 1 in C++
!
- Logical NOT
Inverses the boolean value of the operand
Predecence of Logical Operators
- * / %
- + -
- < <= > >=
- == !=
- && ( Predecence of Logical AND
&&
is prior than logical OR||
)1 && 0 || 1 && 1 == 0 || 1 == true
- ||
- ? : (RTL)
Compound Statement: Grouped in { }
if
... else if
... else
...
if( ){
}else if( ){
}else{
}
Here are the TRAPS
Be aware of Empty Statements if(1==2); cout<<"1 = 2";
Where I Fell in the Mid-Term
Nester: an if-else statement is included in an if or else statement (Nearest Predecence)
Be aware of =
and ==
=
operators always return true, unless RHS == 0 ie false
Short-Circuit Evaluation
Only execute the Former Operand when the outcome is known
- For &&: when former-statement == false (already known to be false)
- For || when former-statement == true (already known to be true)
Official explanation: Improve program efficiency
switch
statement
- The switch expression must be an Integer (int, long, short, char)
- The case const-expression must be constsnts
switch (expression){
case const-expr1: // the case expression must be Constant
statement-1;
break;
case const-exprn:
statement-n;
break;
default:
statement-default;
}
Conditional Operator: expr1 ? expr2 : expr3
- Sequence of Evaluation:
- expr1 is evaluated
- if true, expr 2 is evaluated and returned
- if false, expr 3 is evaluated and returned