enum

Allows the creation of user defined (enumerated) data types.

 

Enumerated data types consist of a value defined as a symbolic constant, known as an enumerator, starting from zero.

 

#include <iostream>

using namespace std ;

enum ResistorBand {
	Black,	//assigned 0
	Brown,	//assigned 1
	Red,	//assigned 2
	Orange,	//assigned 3
	Yellow,	//assigned 4
	Green,	//assigned 5
	Blue,	//assigned 6
	Violet,	//assigned 7
	Grey,	//assigned 8
	White	//assigned 9
};

int main () {

	ResistorBand myValue = Green ;
	cout << "The enum in the 5th element is Green with a value of: " << myValue << endl;

	return 0;
}

Compile & Run:

The enum in the 5th element is Green with a value of: 5

 

 

The defined variable (myValue from above) could have been declared along with the enum definition, as per line 16:

#include <iostream>

using namespace std ;

enum ResistorBand {
	Black,	//assigned 0
	Brown,	//assigned 1
	Red,	//assigned 2
	Orange,	//assigned 3
	Yellow,	//assigned 4
	Green,	//assigned 5
	Blue,	//assigned 6
	Violet,	//assigned 7
	Grey,	//assigned 8
	White	//assigned 9
} myValue ;

int main () {

	myValue = Green ;
	cout << "The enum in the 5th element is Green with a value of: " << myValue << endl;

	return 0;
}

Compile & Run:

The enum in the 5th element is Green with a value of: 5

 

 

Specific values can also be defined:

#include <iostream>

using namespace std ;

enum ResistorBand {
	Black,	//assigned 0
	Brown,	//assigned 1
	Red,	//assigned 2
	Orange,	//assigned 3
	Yellow,	//assigned 4
	Green = 42,	//assigned 5
	Blue,	//assigned 6
	Violet,	//assigned 7
	Grey,	//assigned 8
	White	//assigned 9
} myValue ;

int main () {

	myValue = Green ;
	cout << "The enum in the 5th element is Green with a value of: " << myValue << endl;

	return 0;
}

Compile & Run:

The enum in the 5th element is Green with a value of: 42

Leave a Reply