Home arrow C and C+ arrow Using enum in C and C++
Using enum in C and C++ PDF
Monday, 16 May 2011
With enum we can define new types of data that describe an enumeration of things.

To define an enum we use:
defining an enum type
enum  enum_name {
  val1,
  val2,
  val3,
}

enum_name MyEnumVar;


It is also possible to omit enum_name. This is useful if you want to define some constants but you want not to asign a value for every one of them using #define. So instead you will use:
defining enum type, ommiting enum_name
enum {
  VAL1,
  VAL2,
  VAL3,
};

Here are some examples of using enum:

example1
include <iostream>

using namespace std;

int main(void)
{
  enum names{John,Jimmy,Mike,Tom};

  names aName;

  aName=names(0);

  if ( aName == John)
    cout << "It's John" << endl;

  aName=Mike;

  if ( aName == Mike)
    cout << "It's Mike" << endl;
}

Example 2

example2
#include <iostream>

using namespace std;

int main(void)
{
  enum names{John,Jimmy,Mike,Tom};

  names aName;

  aName = names(Mike);
  cout << aName << endl;

}

Example 3

example3
#include <iostream>

using namespace std;

int main(void)
{
  enum names{John=10,Jimmy=20,Mike=30,Tom=40};

  names aName;

  aName = names(Tom);
  cout << aName << endl;

}

Example 4

example 4
#include <iostream>

using namespace std;

int main(void)
{
  enum names{John=10,Jimmy=20,Mike=30,Tom=40};

  int sum;
  names aName;

  aName = names(Tom);

  sum = John + Jimmy;
  cout << sum << endl;
}




Last Updated ( Monday, 16 May 2011 )
 
< Prev   Next >

Other BSD Systems

OpenBSD

Misc

Solaris

Polls

Best BSD firewall?