Core C++

Enums Program 5

Overview

In this C++ example, we demonstrate how to use an enum to define a type that could be used to represent the numbers of a Fibonacci sequence.
 

Example

#include <iostream>


// We can define an enum to represent numbers of a Fibonacci sequence.
// We can use formulas and the previous values to assign new values.
// In this case, keF1 = 1, keF2 = 1, keF3 = 2, keF4 = 3.
enum EFibonacci {keF1 = 1, keF2 = keF1, keF3, keF4 = keF2 + keF3};

int main() {
    using namespace std;

    // Create an instance of the type and assign it the value keF4.
    EFibonacci eMyFib(keF4);

    cout << "Fibonacci enum value = " << eMyFib << endl;
    // Output the constant enum values.
    cout << "keF1 = " << keF1 << endl;
    cout << "keF2 = " << keF2 << endl;
    cout << "keF3 = " << keF3 << endl;
	cout << "keF4 = " << keF4 << endl;

    // Keep the console window open.
    cin.get();
    return 0;
}

Output

 
 

© 2007–2025 XoaX.net LLC. All rights reserved.