Selection

判断选择

​If

if (boolean expression) {
执行内容
}

if (boolean expression)
//single statement
if 结构

If-else

if (boolean expression) {
    //do if true
} else {
    //do if false
}
if-else 结构

Multiple if-else

if (boolean expression) {
    //do stuff
} else if (boolean expr) {
    //do other stuff
} else {
    //do yet other stuff
}
Multiple if-else 结构(多种条件判断)

Switch

switch (value) {
    case val1:
        //do stuff
        break;
    case val2:
        //do other stuff
        break;
    default:
        //yet other stuff
}
Switch结构(不同case)

Switch with fall-through

switch (value) {
    case val1:
        //do stuff
    case val2:
        //do other stuff
        break;
    default:
        //yet other stuff
}
Switch with fall-through结构

Switch

  • Value used for comparison must be an integer, char, or enumeration.

    • enumeration = identifier that maps to an integer

  • When a matching case is found, code is executed until encountering a break. This can result in code for multiple cases executing (fall-through)

    • Tip: when debugging, check for missing or mistaken break statements

Last updated

Was this helpful?