Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


Tip of the Day
Home » Tip Bank » C++
Language: C++
Expertise: All
Apr 10, 1998

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 file

enum Month { Jan, 
		Feb,
		Mar,
		//...etc.
		Dec};

//Month.cpp file

int 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
Danny Kalev
 
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap
Thanks for your registration, follow us on our social networks to keep up-to-date