dcsimg
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

By submitting your information, you agree that devx.com may send you DevX offers via email, phone and text message, as well as email offers about other products and services that DevX believes may be of interest to you. DevX will process your information in accordance with the Quinstreet Privacy Policy.


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

WEBINAR:

On-Demand

Building the Right Environment to Support AI, Machine Learning and Deep Learning


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