Control Flow - Conditional Statement

LT4 Control Flow - Conditional Statements

Syntax Summary

  1. Keywords
    • if, else
    • switch, case, default
    • break, continue
  2. Punctuators
    • (), {},
    • :
    • ? :
  3. 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
  1. * / %
  2. + -
  3. < <= > >=
  4. == !=
  5. && ( Predecence of Logical AND && is prior than logical OR || )
    • 1 && 0 || 1 && 1 == 0 || 1 == true
  6. ||
  7. ? : (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:
  1. expr1 is evaluated
    1. if true, expr 2 is evaluated and returned
    2. if false, expr 3 is evaluated and returned

你可能感兴趣的:(Control Flow - Conditional Statement)