Switch on a char in C++

Level 3154 keystrokes

A char is an integer type, so it can be used in switch with character literals as case labels. grade is 'B', so "Good" is printed.

C++ code

// A character literal uses single quotes
1char grade = 'B';
// Compares grade with each character label
2switch (grade) {
3 case 'A': cout << "Excellent"; break;
// 'B' matches: prints Good, then break leaves the switch
4 case 'B': cout << "Good"; break;
// There is no default, so any other grade would print nothing
5 case 'C': cout << "Fair"; break;
6}
// Ends the line
7cout << endl;

Output

Good
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this C++ code and how often they appear.

  • ;× 8
  • '× 8
  • <× 8
  • "× 6
  • :× 3
  • (× 1
  • )× 1
  • {× 1
  • }× 1
  • =× 1

More C++ examples at level 3

← C++ typing practice