Programming & Scripting Tutorials

C++: Switch Statements





In this lesson we are just going get a bit easier for once with switch statements.
Switch statements are a lot like if statements, but you use them to compare one value in various different cases.
For example:


#include <iostream>

using namespace std;

int main(){
int Int1;
cin >> Int1;
switch (Int1){
case 0:
	cout << "Zero is my favorite number" << endl;
	break;
case 1:
	cout << "I hate the number one" << endl;
	break;
case 5:
	cout << "Five is an OK number..." << endl;
	break;
default:
	cout << "No case specified" << endl;
}
system("PAUSE");
return 0;
}


As you can see it does exactly what it says on the tin.
It checks if the value is 0, 1 or 5, then does things appropriately, if it isn't any of the cases we specified it goes to default.

To make this a bit more difficult and up it to the advanced level we are at, try and see if you can figure out what this would do:


#include <iostream>
#include <conio.h>

using namespace std;

class ClassOne{
public:
int energy;
int speed;
int endurance;
ClassOne(){
Setattributes(0, 0, 0);
}
ClassOne(int e){
Setattributes(e, 0, 0);
}
ClassOne(int e, int s){
Setattributes(e, s, 0);
}
ClassOne(int e, int s, int en){
Setattributes(e, s, en);
}
void Setattributes(int energy, int speed, int endurance){
this->energy = energy;
this->speed = speed;
this->endurance = endurance;
}
virtual void PrintAttributes(){
	cout << "Energy " << this->energy << "\nSpeed " << this->speed << "\nEndurance " << this->endurance << endl << endl;
}
};

class Two : public ClassOne{
	virtual void PrintAttributes(){
		cout << "Two not programmed to do selected task(s).." << endl << endl;
}

};


int main(){
Two Object1;

ClassOne* Ptr1;

Ptr1 = &Object1;

Ptr1->Setattributes(3, 0, 3);
Ptr1->PrintAttributes();
switch(Ptr1->energy){
case 1:
	cout << "1" << endl;
	break;
case 3:
	cout << "Energy = 3!!" << endl;
		break;
default:
	cout << "No Case Specified for Energy" << endl;
}
switch(Ptr1->speed){
case 1:
	cout << "1" << endl;
	break;
case 3:
	cout << "Speed = 3!!" << endl;
		break;
default:
	cout << "No Case Specified for Speed" << endl;
}
switch(Ptr1->endurance){
case 1:
	cout << "1" << endl;
	break;
case 3:
	cout << "Endurance = 3!! Thats really bad!!" << endl;
		break;
default:
	cout << "No Case Specified for Endurance" << endl;
}

getch();
return 0;
}


Can you figure it out??


BEWARE SPOILER BELOW!

If you haven’t figured it out, it outputs:


Two not programmed to do selected task(s)..

Energy = 3!!
No Case Specified for Speed
Endurance = 3!! Thats really bad!!


This C++ tutorial was written by


Back to C++

Advertisement: