Software & Finance





C++ - Enumerations





There is a very clear difference between #define macro and enumerations, event it may confuse some people. enumeration is not a macro and it stays even after compilation. enums are used when there is logical grouping of elements are necessary.

 

The first element in the enum has default value set to 0, if there is no value assigned. The next elements has follow the simple formula of the value of the previous element plus 1.

 

Look at the sample code and output. It is easy to understand.


Source Code


void main()

{

   enum Location {

        LocUSA, LocUK, LocGermany, LocIndia, LocChina, LocJapan,

          LocPhilippines, LocMalaysia, LocSingapore, LocThailand,

          LocIndonesia, LocOthers

    }; 

    enum Random {

        randData1 = -23, randData2, randData3, randData4 = 10, randData5

    }; 

    std::cout << "USA: " << LocUSA << "\n";

    std::cout << "India: " << LocIndia << "\n"; 

    std::cout << "randData2: " << randData2 << "\n";

    std::cout << "randData5: " << randData5 << "\n";

}

 

Output


USA: 0

India: 3

randData2: -22

randData5: 11

 

Press any key to continue . . .