logo

Enum v C

Enum v C je znan tudi kot našteti tip. To je uporabniško definiran podatkovni tip, ki je sestavljen iz celoštevilskih vrednosti, in tem vrednostim zagotavlja smiselna imena. Uporaba enuma v C olajša razumevanje in vzdrževanje programa. Enum je definiran z uporabo ključne besede enum.

Naslednji je način za definiranje enuma v C:

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

V zgornji deklaraciji definiramo enum, imenovan kot zastavica, ki vsebuje 'N' celih konstant. Privzeta vrednost integer_const1 je 0, integer_const2 je 1 in tako naprej. Prav tako lahko spremenimo privzeto vrednost celih konstant v času deklaracije.

Na primer:

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

Privzeta vrednost za mango je 0, jabolko je 1, jagoda je 2 in papaja je 3. Če želimo spremeniti te privzete vrednosti, lahko storimo, kot je navedeno spodaj:

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

Deklaracija oštevilčenega tipa

Kot vemo, moramo v jeziku C deklarirati spremenljivko vnaprej določenega tipa, kot je int, float, char itd. Podobno lahko deklariramo spremenljivko uporabniško definiranega podatkovnega tipa, kot je enum. Poglejmo, kako lahko deklariramo spremenljivko tipa enum.

Recimo, da ustvarimo enum statusa tipa, kot je prikazano spodaj:

 enum status{false,true}; 

Zdaj ustvarimo spremenljivko statusnega tipa:

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

V zgornjem stavku smo deklarirali spremenljivko 's' statusa tipa.

Če želite ustvariti spremenljivko, lahko zgornja dva stavka zapišete kot:

 enum status{false,true} s; 

V tem primeru bo privzeta vrednost false enaka 0, vrednost true pa 1.

Ustvarimo preprost program enum.

 #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; } 

V zgornji kodi ustvarimo tip enum, imenovan dnevi v tednu, in vsebuje ime vseh sedmih dni. Nedelji smo dodelili 1 vrednost, vsa druga imena pa bodo dobila vrednost kot prejšnja vrednost plus ena.

Izhod

Enum v C

Pokažimo še en primer, da bomo enum bolj jasno razumeli.

 #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++)>

Izhod

Enum v C

Nekaj ​​pomembnih točk, povezanih z enum

  • Imena enumov, ki so na voljo v tipu enum, imajo lahko enako vrednost. Poglejmo primer.
 #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; } 

Izhod

Enum v C
  • Če imenom enum ne zagotovimo nobene vrednosti, bo prevajalnik samodejno dodelil privzete vrednosti imenom enum, začenši z 0.
  • Ime enum lahko dodamo tudi v poljubnem vrstnem redu, nedodeljena imena pa bodo dobila privzeto vrednost kot prejšnja plus ena.
  • Vrednosti, dodeljene imenom enum, morajo biti integralna konstanta, tj. ne smejo biti drugih vrst, kot so niz, plavajoči itd.
  • Vsa imena enumov morajo biti unikatna v svojem obsegu, tj. če definiramo dva enuma z enakim obsegom, morata ta dva enuma imeti različna imena enumov, sicer bo prevajalnik vrgel napako.

Razumejmo ta scenarij na primeru.

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

Izhod

Enum v C
  • Pri naštevanju lahko definiramo oštevilčeni podatkovni tip tudi brez imena.
 #include enum {success, fail} status; int main(void) { status=success; printf(&apos;The value of status is %d&apos;, status); return 0; } 

Izhod

Enum v C

Enum proti makru v C

  • Makro lahko uporabite tudi za definiranje imenskih konstant, toda v primeru enuma lahko vse imenske konstante združite v en sam stavek.
    na primer
    # definiraj prehod 0;
    # definiraj uspeh 1;
    Zgornja dva stavka je mogoče zapisati v en stavek z uporabo tipa enum.
    enum status{pass, success};
  • Tip enum sledi pravilom obsega, medtem ko makro ne sledi pravilom obsega.
  • Če v Enumu ne dodelimo vrednosti imenom enum, bo prevajalnik samodejno dodelil privzeto vrednost imenom enum. Toda v primeru makra morajo biti vrednosti izrecno dodeljene.
  • Vrsta enuma v C je celo število, vrsta makra pa je lahko katere koli vrste.