Home > Articles

  • Print
  • + Share This
This chapter is from the book

Enumerated Constants

Enumerated constants create a set of constants. For example, you can declare COLOR to be an enumeration; and you can define that there are five values for COLOR: RED, BLUE, GREEN, WHITE, and BLACK.

The syntax for enumerated constants is to write the keyword enum, followed by the type name, an open brace, each of the legal values separated by a comma, and finally a closing brace and a semicolon. Here's an example:


This statement performs two tasks:

  1. It makes COLOR the name of an enumeration, that is, a new type.

  2. It makes RED a symbolic constant with the value 0, BLUE a symbolic constant with the value 1, GREEN a symbolic constant with the value 2, and so forth.

Every enumerated constant has an integer value. If you don't specify otherwise, the first constant will have the value 0, and the rest will count up from there. Any one of the constants can be initialized with a particular value, however, and those that are not initialized will count upward from the ones before them. Thus, if you write

enum Color { RED=100, BLUE, GREEN=500, WHITE, BLACK=700 };

then RED will have the value 100; BLUE, the value 101; GREEN, the value 500; WHITE, the value 501; and BLACK, the value 700.

The advantage of this technique is that you get to use a symbolic name such as BLACK or WHITE instead of a possibly meaningless number such as 1 or 700.

It is common practice to use all capital letters for regular and enumerated constant names. This makes it visually obvious that the name you are reading is a constant and not some variable you are allowed to change. The compiler itself does not care so long as you are consistent.

  • + Share This
  • 🔖 Save To Your Account