logo

Enum C

C enum taip pat žinomas kaip išvardintas tipas. Tai vartotojo apibrėžtas duomenų tipas, susidedantis iš sveikųjų skaičių reikšmių ir suteikiantis prasmingus šių reikšmių pavadinimus. Naudojant enum C kalboje, programa yra lengvai suprantama ir prižiūrima. Enum apibrėžiamas naudojant enum raktinį žodį.

Toliau pateikiamas būdas apibrėžti enumą C:

 enum flag{integer_const1, integer_const2,.....integter_constN}; 

Aukščiau pateiktoje deklaracijoje apibrėžiame sąrašą, pavadintą kaip vėliavėlę, kurioje yra „N“ sveikųjų skaičių konstantų. Numatytoji integer_const1 reikšmė yra 0, integer_const2 yra 1 ir pan. Taip pat galime pakeisti numatytąją sveikųjų skaičių konstantų reikšmę deklaravimo metu.

Pavyzdžiui:

 enum fruits{mango, apple, strawberry, papaya}; 

Numatytoji mango reikšmė yra 0, obuolių yra 1, braškių yra 2 ir papajų yra 3. Jei norime pakeisti šias numatytąsias reikšmes, galime elgtis taip, kaip nurodyta toliau:

 enum fruits{ mango=2, apple=1, strawberry=5, papaya=7, }; 

Išvardinto tipo deklaracija

Kaip žinome, C kalba turime deklaruoti iš anksto nustatyto tipo kintamąjį, pvz., int, float, char ir tt Panašiai galime deklaruoti vartotojo apibrėžto duomenų tipo kintamąjį, pvz., enum. Pažiūrėkime, kaip galime deklaruoti enum tipo kintamąjį.

Tarkime, kad sukuriame tipo būsenos sąrašą, kaip parodyta toliau:

 enum status{false,true}; 

Dabar sukuriame būsenos tipo kintamąjį:

 enum status s; // creating a variable of the status type. 

Aukščiau pateiktame teiginyje deklaravome tipo būsenos kintamąjį „s“.

Norėdami sukurti kintamąjį, aukščiau pateikti du teiginiai gali būti parašyti taip:

 enum status{false,true} s; 

Tokiu atveju numatytoji false reikšmė bus lygi 0, o true reikšmė bus lygi 1.

Sukurkime paprastą enum programą.

 #include enum weekdays{Sunday=1, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday}; int main() { enum weekdays w; // variable declaration of weekdays type w=Monday; // assigning value of Monday to w. printf('The value of w is %d',w); return 0; } 

Aukščiau pateiktame kode sukuriame enum tipą, pavadintą savaitės dienomis, ir jame yra visų septynių dienų pavadinimai. Sekmadieniui priskyrėme 1 reikšmę, o visiems kitiems pavadinimams bus suteikta reikšmė kaip ankstesnė vertė plius vienas.

Išvestis

Enum C

Parodykime kitą pavyzdį, kad aiškiau suprastume enum.

 #include enum months{jan=1, feb, march, april, may, june, july, august, september, october, november, december}; int main() { // printing the values of months for(int i=jan;i<=december;i++) { printf('%d, ',i); } return 0; < pre> <p>In the above code, we have created a type of enum named as months which consists of all the names of months. We have assigned a &apos;1&apos; value, and all the other months will be given a value as the previous one plus one. Inside the main() method, we have defined a for loop in which we initialize the &apos;i&apos; variable by jan, and this loop will iterate till December.</p> <p> <strong>Output</strong> </p> <img src="//techcodeview.com/img/c-tutorial/73/enum-c-2.webp" alt="Enum in C"> <h3>Why do we use enum?</h3> <p>The enum is used when we want our variable to have only a set of values. For example, we create a direction variable. As we know that four directions exist (North, South, East, West), so this direction variable will have four possible values. But the variable can hold only one value at a time. If we try to provide some different value to this variable, then it will throw the compilation error.</p> <p>The enum is also used in a switch case statement in which we pass the enum variable in a switch parenthesis. It ensures that the value of the case block should be defined in an enum.</p> <p> <strong>Let&apos;s see how we can use an enum in a switch case statement.</strong> </p> <pre> #include enum days{sunday=1, monday, tuesday, wednesday, thursday, friday, saturday}; int main() { enum days d; d=monday; switch(d) { case sunday: printf(&apos;Today is sunday&apos;); break; case monday: printf(&apos;Today is monday&apos;); break; case tuesday: printf(&apos;Today is tuesday&apos;); break; case wednesday: printf(&apos;Today is wednesday&apos;); break; case thursday: printf(&apos;Today is thursday&apos;); break; case friday: printf(&apos;Today is friday&apos;); break; case saturday: printf(&apos;Today is saturday&apos;); break; } return 0; } </pre> <p> <strong>Output</strong> </p> <img src="//techcodeview.com/img/c-tutorial/73/enum-c-3.webp" alt="Enum in C"> <p> <strong>Some important points related to enum</strong> </p> <ul> <li>The enum names available in an enum type can have the same value. Let&apos;s look at the example.</li> </ul> <pre> #include int main(void) { enum fruits{mango = 1, strawberry=0, apple=1}; printf(&apos;The value of mango is %d&apos;, mango); printf(&apos;
The value of apple is %d&apos;, apple); return 0; } </pre> <p> <strong>Output</strong> </p> <img src="//techcodeview.com/img/c-tutorial/73/enum-c-4.webp" alt="Enum in C"> <ul> <li>If we do not provide any value to the enum names, then the compiler will automatically assign the default values to the enum names starting from 0.</li> <li>We can also provide the values to the enum name in any order, and the unassigned names will get the default value as the previous one plus one.</li> <li>The values assigned to the enum names must be integral constant, i.e., it should not be of other types such string, float, etc.</li> <li>All the enum names must be unique in their scope, i.e., if we define two enum having same scope, then these two enums should have different enum names otherwise compiler will throw an error.</li> </ul> <p> <strong>Let&apos;s understand this scenario through an example.</strong> </p> <pre> #include enum status{success, fail}; enum boolen{fail,pass}; int main(void) { printf(&apos;The value of success is %d&apos;, success); return 0; } </pre> <p> <strong>Output</strong> </p> <img src="//techcodeview.com/img/c-tutorial/73/enum-c-5.webp" alt="Enum in C"> <ul> <li>In enumeration, we can define an enumerated data type without the name also.</li> </ul> <pre> #include enum {success, fail} status; int main(void) { status=success; printf(&apos;The value of status is %d&apos;, status); return 0; } </pre> <p> <strong>Output</strong> </p> <img src="//techcodeview.com/img/c-tutorial/73/enum-c-6.webp" alt="Enum in C"> <h3>Enum vs. Macro in C</h3> <ul> <li>Macro can also be used to define the name constants, but in case of an enum, all the name constants can be grouped together in a single statement. <br> For example, <br> # define pass 0; <br> # define success 1; <br> The above two statements can be written in a single statement by using the enum type. <br> enum status{pass, success};</li> <li>The enum type follows the scope rules while macro does not follow the scope rules.</li> <li>In Enum, if we do not assign the values to the enum names, then the compiler will automatically assign the default value to the enum names. But, in the case of macro, the values need to be explicitly assigned.</li> <li>The type of enum in C is an integer, but the type of macro can be of any type.</li> </ul> <hr></=december;i++)>

Išvestis

Enum C

Kai kurie svarbūs dalykai, susiję su enum

  • Eenum tipo pavadinimai gali turėti tą pačią reikšmę. Pažiūrėkime į pavyzdį.
 #include int main(void) { enum fruits{mango = 1, strawberry=0, apple=1}; printf(&apos;The value of mango is %d&apos;, mango); printf(&apos;
The value of apple is %d&apos;, apple); return 0; } 

Išvestis

Enum C
  • Jei sąrašo pavadinimams nepateiksime jokios reikšmės, kompiliatorius automatiškai priskirs numatytąsias reikšmes sąrašo pavadinimams, pradedant nuo 0.
  • Be to, sąrašo pavadinimo reikšmes galime pateikti bet kokia tvarka, o nepriskirtiems pavadinimams bus suteikta numatytoji reikšmė kaip ankstesnė plius viena.
  • Sąrašų pavadinimams priskirtos reikšmės turi būti integralios konstantos, t.y., ji neturėtų būti kitų tipų, tokių kaip eilutė, float ir pan.
  • Visi enum pavadinimai turi būti unikalūs savo apimtimi, t.

Supraskime šį scenarijų per pavyzdį.

 #include enum status{success, fail}; enum boolen{fail,pass}; int main(void) { printf(&apos;The value of success is %d&apos;, success); return 0; } 

Išvestis

Enum C
  • Sąrašuose galime apibrėžti surašytų duomenų tipą ir be pavadinimo.
 #include enum {success, fail} status; int main(void) { status=success; printf(&apos;The value of status is %d&apos;, status); return 0; } 

Išvestis

Enum C

Enum prieš makrokomandą C

  • Makrokomandą taip pat galima naudoti pavadinimo konstantoms apibrėžti, tačiau, jei yra enum, visas vardo konstantas galima sugrupuoti į vieną sakinį.
    Pavyzdžiui,
    # apibrėžti praėjimą 0;
    # apibrėžti sėkmę 1;
    Aukščiau pateikti du teiginiai gali būti parašyti viename sakinyje naudojant enum tipą.
    enum statusas {pasl., sėkmės};
  • Enum tipas atitinka taikymo srities taisykles, o makrokomandos nesilaiko taikymo srities taisyklių.
  • Jei Enum reikšmių nepriskirsime enum pavadinimams, tada kompiliatorius automatiškai priskirs numatytąją reikšmę enum pavadinimams. Tačiau makrokomandos vertės turi būti aiškiai priskirtos.
  • C enum tipas yra sveikasis skaičius, tačiau makrokomandos tipas gali būti bet kokio tipo.