Using Enumerators as Labels
Listing 6.11 illustrates using enum
to define a set of related constants and then using the constants in a switch
statement. In general, cin
doesn’t recognize enumerated types (it can’t know how you will define them), so the program reads the choice as an int
. When the switch
statement compares the int
value to an enumerator case label, it promotes the enumerator to int
. Also the enumerators are promoted to type int
in the while
loop test condition.
// enum.cpp -- using enum#include <iostream>// create named constants for 0 - 6enum {red, orange, yellow, green, blue, violet, indigo};int main(){ using namespace std; cout << "Enter color code (0-6): "; int code; cin >> code; while ...
Get C++ Primer Plus now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.