Introduction to Programming and C++

Contents Previous Topic Next Topic

Suppose you have a number of possible operations which may be performed based on the value of a built-in data type.

	if ( n == 0 ) {
		// case 0
	} else if ( n == 1 ) {
		// case 1
	} else if ( n == 2 ) {
		// case 2
	} ... {
		// case N - 1
	} else if ( n == N ) {
		// case N
	} else {
		// all other cases
	}

Such a structure would run in linear time with respect to the number of case... A switch statement is an alternative.

Note, a switch statement is not just another way of writing Code Fragment 1. It uses a completely different mechanism for finding the appropriate piece of code to execute so that it runs in O(1) time, instead of O(N).


Contents Previous Topic Top Next Topic