devxlogo

Make sure your switch statements always have a default label

Make sure your switch statements always have a default label

A safe-to-use, long-lasting switch statement should always contain a default label in order to avoid hard-to-detect bugs such as the following:

 //Month.h fileenum Month { Jan, 		Feb,		Mar,		//...etc.		Dec};//Month.cpp fileint daysInMonth(Month month) {		int result = 0;		switch (month) {			case Jan:				result = 31;			break;			case Feb:				result = 28;			break;			//...Mar to Nov go here			case Dec:				result = 31;			break;			//no default		} //end switch	return result;	}//end daysInMonth() 

Now suppose some other programmer needs to extend the Month enumeration later in the following manner:

 //file Month.h re-edited	enum Month { Jan, 			Feb,			LeapFeb, //newly added 			Mar,			//...etc.			Dec};

As a result, the switch statement above will return the wrong result; for example, 0, to its user’s amazement when its month is LeapFeb. Had a default label been used, this bug could have been detected easily:

 		switch (month) { //now with a default		case Jan:			result = 31;		break;		case Feb:			result = 28;		break;		//...Mar to Nov go here		case Dec:			result = 31;		break;		deafult:			cout<<"unsupported month value;check this switch!";		break;	} //end switch

devx-admin

Share the Post: