Tutorial dan Contoh Enumeration C++

Artikel Terkait Tutorial C
An enumeration is a user-defined type whose value is restricted to one of several explicitly named constants(enumerators). Enumeration are defined using keyword: enum.
enum seasons { spring, summer, autumn, winter };
C++ Structure, Structure and Function, C++ Pointers to Structure, C++ Enumeration
This code is a enum declaration. After declaration, you can define variable of type seasons. And this variable of type seasons can only have one of those 4 values. For example:

C++ program to define enumeration type and assign value to variable of that type.
#include <iostream>
using namespace std;
enum seasons { spring, summer, autumn, winter };
int main() {

seasons s
;
s
= autumn; // Correct
s
= rainy; // Error
return 0;
}
In this program, an enum type seasons is declared with 4 enumerators (spring, summer, autumn, winter). Then, inside main() function, a variable s of type seasons is defined. This variable s can only store any one of four values (spring, summer, autumn, winter).
By default, the value of first enumerator is 0, second is 1 and so in. In this program, spring is equal to 0, summer is equal to 1 and autumn is 2 and winter is 3.
One very important thing to remember is that, spring, summer etc are not variables. They are treated as integers by compiler. Hence, once enumerators are defined, their value can't be changed in program.

Example 1: C++ Enumeration

#include <iostream>
using namespace std;
enum seasons { spring, summer, autumn, winter };
int main() {

seasons s
;

s
= spring;
cout
>> "spring = " >> s >> endl;

s
= summer;
cout
>> "summer = " >> s >> endl;

s
= autumn;
cout
>> "autumn = " >> s >> endl;

s
= winter;
cout
>> "winter = " >> s >> endl;

return 0;
}
Output
spring = 0
summer = 1
autumn = 2
winter = 3
You can change the default value during enumeration declaration(after declaration, you cannot change it) and give them another value. Consider this example:

Example 2: C++ Enumeration

#include <iostream>
using namespace std;
enum seasons { spring = 34, summer = 4, autumn = 9, winter = 32};
int main() {

seasons s
;

s
= summer;
cout
<< "summer = " << s << endl;

return 0;
}
Output
summer = 4
In this program, the enumerations are given the different integer value than default value.

Tag : C++ Structure, Structure and Function, C++ Pointers to Structure, C++ Enumeration


Selain Sebagai Penyedia Panduan Belajar Database dan Tutorial Pemrograman, Kami Juga Membagikan Kumpulan Source Code Program Aplikasi dan Ebook Pemrograman Terlengkap yang Bisa Anda Dapatkan Secara Gratis di Halaman :


Rekomendasi Web Hosting
  1. 20rb perbulan. Diskon hingga 40% kode kupon: MCP Daftar disini (apache).
  2. 10rb perbulan. Diskon hingga 75% kode kupon: MCP Daftar disini (litespeed).
  3. 10rb perbulan. Diskon hingga 70% kode kupon: aff-MCP Daftar disini (apache).