1. Home
  2. Computing & Technology
  3. C / C++ / C#

C++ Handling Ints and Floats

By , About.com Guide

8 of 8

Use Enums for Better Code

For a more in depth look at enums, read this article first. An enum is another type that is based on int.

An enum type provides a way to restrict a variable to one of a fixed set of values.

enum rainbowcolor {red,orange,green, yellow, blue,indigo,violet};
By default these are assigned the values 0 to 6 (red is 0, violet is 6). You can define your own values instead of using the compiler values e.g.
enum rainbowcolor {red=1000,orange=1005,green=1009, yellow=1010, blue,indigo,violet};
The remaining unassigned colors will be assigned 1011, 1012 and 1013. The values continue sequentially from the last assigned value which was yellow=1010.

You can assign an enum value to an int as in

int p=red;
but not the other way round. That's the restriction and it prevents assignment of meaningless values. Even assigning a value that corresponds to an enum constant is an error.
rainbowcolor g=1000; // Error!
The requires
rainbowcolor g=red;
This is type safety in action. Only valid values of the enumeration range can be assigned. This is part of the general C++ philosophy that it is better for the compiler to catch errors at compile time than the user at runtime.

Even though the two statements are conceptually the same. In fact you'll usually find that these two seemingly identical lines

int p =1000;
rainbowcolor r = red;
are both likely to have identical machine code generated by the compiler. Certainly they do in Microsoft Visual C++.

That completes this tutorial. The next tutorial is about expressions and statements.

Explore C / C++ / C#
About.com Special Features

Holiday Central

What to eat, where to go, fun things to do and how to save money on the perfect gifts. More >

Family Tech Center

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

  1. Home
  2. Computing & Technology
  3. C / C++ / C#
  4. C++
  5. Learn C++ Programming
  6. Use Enums for Better Code

©2009 About.com, a part of The New York Times Company.

All rights reserved.