switch Statement

If you managed to solve the previous exercise, you probably had implemented a function or just a sequence of if statement to return number of days in each month. A switch statement does not bring any new functionality, but allows to write comparisons against multiple values in a somewhat more straightforward way:

switch (expression) {
	case 0:
		printf("it is zero\n");
		break;
	case 1:
		printf("it is one\n");
	case 2:
		printf("it is either one or two!\n");
		break;
	default:
		printf("it is something else\n");
}

In this example, the value of expression will be compared to 0, 1, and 2. Note the break; statements: if you omit the break;, the subsequent statements will be executing. Look at the case 1: branch: if the value of expression is 1, it will print it is one, but then will also print it is either one or two!, because there is no break at the end of case 1: branch. This behavior is called "fallthrough".

Of course, you can use return instead of break if there's nothing to do after the switch.

Here is how you would write the number_of_days function with switch:

int number_of_days(int y, int m) {
	switch (m) {
		case 1:
		case 3:
		case 5:
		case 7:
		case 8:
		case 10:
		case 12:
			return 31;
		case 2:
			if (is_leap_year(y)) {
				return 29;
			}
			return 28;
		default:
			return 30;
	}
}

Note that the values in case: options must be constants; switch cannot compare its expression to a variable.

Changing a sequence of if statements to a switch statement is definitely an improvement to number_of_days, but on the next page we'll learn about the language feature which will allow us to implement number_of_days in a completely new way–and also do a lot of other cool things. We'll finally talk about arrays. Stay tuned!