Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C++

วิธีใช้ Enum ใน C++


การใช้ Enumeration (Enum) ใน C++

Enumeration เป็น user-defined datatype ใช้กำหนดชื่อให้ค่าคงที่จำนวนเต็ม ทำให้โปรแกรมอ่านง่ายและบำรุงรักษาง่าย ใช้คีย์เวิร์ด enum

ไวยากรณ์

enum enum_name { const1, const2, ... };
  • enum_name: ชื่อที่ผู้ใช้ตั้ง
  • const1, const2: ค่าของ flag

มี 2 วิธีประกาศตัวแปร enum:

enum colors { red, black };
enum suit { heart, diamond=8, spade=3, club };

ตัวอย่าง

#include <iostream>
using namespace std;

enum colors { red=5, black };
enum suit { heart, diamond=8, spade=3, club };

int main() {
    cout << "The value of enum color: " << red << "," << black;
    cout << "\nThe default value of enum suit: " << heart << "," << diamond << "," << spade << "," << club;
    return 0;
}

ผลลัพธ์

The value of enum color: 5,6
The default value of enum suit: 0,8,3,4

ในโปรแกรม ประกาศ enum 2 ตัวคือ colors และ suit นอก main() แล้วพิมพ์ค่าใน main()