int option = 2;
switch (option) {
case 1:
case 2:
std::cout << "Option 1 or Option 2 selected" << std::endl;
break;
case 3:
std::cout << "Option 3 selected" << std::endl;
break;
}
enum State {
STATE_A,
STATE_B,
STATE_C
};
State currentState = STATE_A;
switch (currentState) {
case STATE_A:
// do something
currentState = STATE_B;
[[fallthrough]];
case STATE_B:
// do something
currentState = STATE_C;
break;
case STATE_C:
// do something
break;
}
switch (token) {
case TOKEN_IF:
// handle if statement
[[fallthrough]];
case TOKEN_ELSE:
// handle else statement
break;
}
這些是在實際應用中常見的使用fallthrough的案例,通過合理地運用fallthrough可以提高代碼的可讀性和簡潔性。