Free, tested & ready to use examples : C++ enum example using usage
AnyExample.com
 
Webanyexample.com
 

Example of using enum in C++

abstract 
enum(enumeration) is a user-defined type consisting of a set of enumerators( enumerator --- named integer constant)
compatible 
  • Any modern C++ compiler

The enum is declared as:

enum enum-type-name { enum-list } enum-variable;
In this form, enum-type-name is optional. However, if you want to use enum type in several places, it is better to use another way of enum declaration:
enum enum-type-name { enum-list };

//... (and somewhere below)

enum enum-type-name enum-variable;
Of course, in the second case enum-type-name cannon be omitted.

Example: declaring enumeration type of automobile companies

source code: C++
 
enum e_acomany {
	Audi,
	BMW, 
	Cadillac, 
	Ford,
	Jaguar, 
	Lexus 
	Maybach, 
	RollsRoyce, 
	Saab
};
?>
 

After declaration, it is possible to use enum-type-name as user-defined type. Enumeration variable or constant may take on only values from enum-list.

Following example demonstrates basic enumeration usage:

source code: C++
 
e_acompany my_car_brand;
my_car_brand = RollsRoyce;
//...
 
if (my_car_brand == Ford) 
	cout << "Hello, Ford-car owner!" << endl;
 
 

Enumerators are stored by compiler as an integers: by default, first enumerator is 0, next enumerator value is previous enumerator value + 1. When defining enumeration it is possible to specify integer constant for every enumerator, see example:

source code: C++
 
enum e_acomany {
	Audi=4,
	BMW=5, 
	Cadillac=11, 
	Ford=44,
	Jaguar=45, 
	Lexus, 
	Maybach=55, 
	RollsRoyce=65, 
	Saab=111
};
 

By the rule "next enumerator value is previous + 1", the value of "Lexus" enumerator is 46

Enumerations are sometimes used instead of integer constants, like in this program:

source code: C++
 
#include <iostream>
using namespace std;
 
enum e_usflcnst{
	CATLIFE_FACTOR = 7
};
 
int main()
{
	int age;
	cout << "Enter your age: ";
	cin >> age;
	age /= CATLIFE_FACTOR;
	cout << "If you were cat, you would be " << age << endl;
}
 



warning 
  • There is no way to get enumerator string representation(without additional array-lookup or switch/if series) in classic C++
  • There is no way to automatically convert string to enumerator (without additional array-lookup or switch/if series) in classic C++
tested by AnyExample.com on 2006-07-30
  • Windows XP :: Microsoft Visual C++ 2003
  • Free BSD 5.2 :: gcc 3.3.3
 


 
© AnyExample 2007
License | Privacy | Contact