Many programmers are surprised to find that switch statements aren’t compatible with strings in C/C++.

When attempting to compile, you will see an error:

Visual Studio 2010 —–  error C2450: switch expression of type ‘std::string’ is illegal

Netbeans 6.9.1 —– error: switch quantity not an integer

Here is an example of invalid code

#include <iostream>
#include <string>

using namespace std;

int main(){

	string dayofweek = "wednesday";

	switch(dayofweek){
		case "monday":
			cout << "Watch football" << endl;
			break;
		case "tuesday":
			cout << "steal a car"<< endl;
			break;
		case "wednesday":
			cout << "rob a bank" << endl;
			break;
		case "thursday":
			cout << "count the money" << endl;
			break;
		case "friday":
			cout << "hire a good lawyer" << endl;
			break;
	}
	return 0;
}

The problem is that strings are not a basic type in the C++ language. Whenever a C++ programmer uses basic variables types like int, bool, and char, nothing extra needed. But when a C++ programmer wishes to use strings in a program, they must add #include <string> to the top of the code to enable that functionality. Basic switch statements don’t have the capability to understand “add on” features such as strings and other filestreams.

There is still hope. The people who created the string library were kind enough to include a function to compare strings – strcmp(). The string compare function can be used along with if..else statements to achieve the same logic as a switch statement.

This is the same logic as before without using a switch statement:

#include <iostream>
#include <string>

using namespace std;

int main(){

	string str = "wednesday";

	if ((!strcmp(str.c_str(), "monday"))){
		cout << "Watch football" << endl;
	}else if (!strcmp(str.c_str(), "tuesday")){
        cout << "steal a car"<< endl;
	}else if (!strcmp(str.c_str(), "wednesday")){
        cout << "rob a bank" << endl;
	}else if (!strcmp(str.c_str(), "thursday")){
		cout << "count the money" << endl;
	}else if (!strcmp(str.c_str(), "friday")){
		cout << "hire a good lawyer" << endl;
	}else{ // same as default
		cout << "Enjoy the Weekend" << endl;
	}

	return 0;
}

Leave a Reply

Your email address will not be published.