Switch() over If() statements

Hello, I am quite new to c++ and was wondering what was the advantage of using a switch() statement over an if() statement. Maybe this is due to my lack of understanding of the switch statement?

Sometimes easier to reason about, cleaner, allows fallthrough:
1
2
3
4
5
6
int i /*= xxx*/;
switch(i) {
  case 1: do_something(); break;
  case 0: i = get_number(); //no break, fallthrough
  default: do_something_else(i); break;
}
vs
1
2
3
4
5
6
7
8
9
int i /*= xxx*/;
if(i == 1) {
    do_something();
} else {
    if(i == 1) {
        i = get_number();
    }
    do_something_else(i);
}
Here's an example. This is taken from a program that asks the user to input several score values, determines the grade based on the input, and counts how many A's, B's, etc. were inputed. The switch statement works quite well for this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
	double score;
	int a_count = 0, b_count = 0, c_count = 0, d_count = 0, f_count = 0;

	score = get_score();

	//while & switch statements to determine grade count based on score input

	while (score >= 0) {

		char grade = get_grade(score);

		switch (grade) {

			case 'A':
				a_count++;
				break;
			case 'B':
				b_count++;
				break;
			case 'C':
				c_count++;
				break;
			case 'D':
				d_count++;
				break;
			case 'F':
				f_count++;
				break;
		}

		cout << "Score: " << score << ", Grade: " << grade << endl;
		score = get_score();
	}


So essentially it looks much cleaner and it's easier than writing a bunch of if statements.
Thank you so much for helping me!

Great responses
Topic archived. No new replies allowed.