cpp-cheatsheet icon indicating copy to clipboard operation
cpp-cheatsheet copied to clipboard

switch case logic

Open uxrkhan opened this issue 5 years ago • 2 comments

The switch case explanation is a bit misleading . There should be a break statement after every case for it to function as an if-else statement, otherwise it will evaluate all the cases.

switch (x) {                  // x must be int
    case X1: a; break;        // If x == X1 (must be a const), jump here
    case X2: b; break;        // Else if x == X2, jump here
    default: c;               // Else jump here (optional)
}

uxrkhan avatar Jun 07 '20 15:06 uxrkhan

The switch case explanation is a bit misleading . There should be a break statement after every case for it to function as an if-else statement, otherwise it will evaluate all the cases.

switch (x) {                  // x must be int
    case X1: a; break;        // If x == X1 (must be a const), jump here
    case X2: b; break;        // Else if x == X2, jump here
    default: c;               // Else jump here (optional)
}

Hi, @uxrkhan Switch cases i.e. (X1 and X2) mentioned above have break statements. But the fact is default case should also include a break statement. @mortennobel thanks for creating this cheat sheet. You can insert a break for default case and close this issue.

Neeraj2K18 avatar Jan 06 '21 20:01 Neeraj2K18

The switch case also support char type , not only int type, though char is a kind of int.

switch (x) { // x must be int and char case X1: a; break; // If x == X1 (must be a const), jump here case X2: b; break; // Else if x == X2, jump here default: c; // Else jump here (optional) }

nasirxshah avatar Jul 19 '21 15:07 nasirxshah