
enumerated type is the simplest method for doing so.
An enumerated type is a data type where every possible value is defined as a symbolic constant (called an enumerator). enum keyword is used to declare Enumerated types.
Example:
// define a new enum named Brand
enum Brand
{
// Here are the enumerators
// These define all the possible values this type can hold
Brand_LEE,
Brand_Reebok,
Brand_Cooper,
Brand_Fila
};
// Declare a variable of enumerated type Brand
Brand a_Brand = Brand_Fila;
Memory is not allocated while defining an enumerated type.
When a variable of the enumerated type is declared (such as a_Brand in the example above), memory is allocated for that variable at that time.
Enum variables are the same size as an int variable.
This is because each enumerator is automatically assigned an integer value based on it’s position in the enumeration list.
By default, the first enumerator is assigned the integer value 0, and each subsequent enumerator has a value one greater than the previous enumerator:
enum Brand
{
Brand_LEE, // assigned 0
Brand_Reebok, // assigned 1
Brand_Cooper, // assigned 2
Brand_Fila // assigned 3
};
Brand a_Brand= Brand_Fila;
cout << a_Brand;
The cout statement above prints the value 3.
we can explicitly define the value of enumerator.
Value of enumerator can be positive or negative and can be non-unique.
Any non-defined enumerators are given a value one greater than the previous enumerator.
// define a new enum named Brand
enum Brand
{
Brand_LEE = -3,
Brand_Reebok, // assigned -2
Brand_Cooper, // assigned -1
Brand_Fila = 5,
Brand_Nike // assigned 6
};
typedef
Typedefs allow the programmer to create an alias for a data type, and use the aliased name instead of the actual type name. To declare a typedef, simply use the typedef keyword, followed by the type to alias, followed by the alias name:
typedef long Binary;
// define Binary as an alias for long
// The following two statements are equivalent:
long number;
Binary number;
A typedef does not define new type, but is just another name for an existing type. A typedef can be used anywhere a regular type can be used.
Typedefs are used mainly for documentation and legibility purposes.
Data type names such as char, int, long, double, and bool are good for describing what type of variable something is, but more often we want to know what purpose a variable serves.
In the above example, long number does not give us any clue what type number is holding.
Is it Binary, Hexadecimal, Octal or some other type? Binary number makes it clear what the type of number is.
5.1 cout (output stream) NEXT >>