Thuta Learning
C
AdvancedProgrammingbeginner

Enums

enum က related constants တွေကို နာမည်ပေးပြီးစုထားတဲ့ type ပါ။ Status, level, menu choice, direction စတာတွေကို number အလွတ်ရေးတာထက် enum နဲ့ရေးရင် code ပိုဖတ်ရလွယ်ပါတယ်။

c
#include <stdio.h>

enum Level {
  LOW,
  MEDIUM,
  HIGH
};

int main() {
  enum Level current = MEDIUM;

  if (current == MEDIUM) {
    printf("Current level is medium.");
  }
  return 0;
}

LOW, MEDIUM, HIGH တွေက default အနေနဲ့ 0, 1, 2 ဖြစ်ပါတယ်။ ဒါပေမယ့် code ဖတ်တဲ့လူအတွက် number တွေထက် meaning ရှင်းပါတယ်။

You should see
Current level is medium.

Info

Enum name တွေကို business meaning ပါအောင်ရေးပါ။ ဥပမာ ORDER_PENDING, ORDER_PAID, ORDER_CANCELLED။

ဒီနေရာမှာ လူအများမှားတတ်တယ်

  • Enum value တွေက integer constants ဖြစ်တာကြောင့် type safety အားနည်းနိုင်ပါတယ်။ Value logic ကိုသေချာစစ်ပါ။
Enums | Thuta Learning