logo

Wyliczenie w C

Wyliczenie w C jest również znane jako typ wyliczeniowy. Jest to typ danych zdefiniowany przez użytkownika, który składa się z wartości całkowitych i nadaje tym wartościom znaczące nazwy. Użycie wyliczenia w C sprawia, że ​​program jest łatwy do zrozumienia i utrzymania. Wyliczenie definiuje się za pomocą słowa kluczowego enum.

Poniżej przedstawiono sposób zdefiniowania wyliczenia w C:

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

W powyższej deklaracji definiujemy wyliczenie o nazwie flaga zawierającej „N” stałych całkowitych. Domyślna wartość integer_const1 to 0, integer_const2 to 1 i tak dalej. Możemy także zmienić domyślną wartość stałych całkowitych w momencie deklaracji.

Na przykład:

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

Domyślna wartość mango to 0, jabłko to 1, truskawka to 2, a papaja to 3. Jeśli chcemy zmienić te wartości domyślne, możemy wykonać poniższe czynności:

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

Deklaracja typu wyliczeniowego

Jak wiemy, w języku C musimy zadeklarować zmienną o predefiniowanym typie, takim jak int, float, char itp. Podobnie możemy zadeklarować zmienną o typie danych zdefiniowanym przez użytkownika, np. enum. Zobaczmy, jak możemy zadeklarować zmienną typu wyliczeniowego.

Załóżmy, że tworzymy wyliczenie statusu typu, jak pokazano poniżej:

 enum status{false,true}; 

Teraz tworzymy zmienną typu status:

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

W powyższym stwierdzeniu zadeklarowaliśmy zmienną typu „s”.

Aby utworzyć zmienną, powyższe dwie instrukcje można zapisać jako:

 enum status{false,true} s; 

W tym przypadku domyślna wartość false będzie równa 0, a wartość true będzie równa 1.

Stwórzmy prosty program wyliczeniowy.

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

W powyższym kodzie tworzymy typ wyliczeniowy o nazwie dni tygodnia, który zawiera nazwy wszystkich siedmiu dni. Niedzieli przypisaliśmy 1 wartość, a wszystkim innym nazwom zostanie nadana wartość taka jak poprzednia wartość plus jeden.

Wyjście

Wyliczenie w C

Zademonstrujmy inny przykład, aby lepiej zrozumieć wyliczenie.

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

Wyjście

Wyliczenie w C

Kilka ważnych punktów związanych z wyliczeniem

  • Nazwy wyliczeniowe dostępne w typie wyliczeniowym mogą mieć tę samą wartość. Spójrzmy na przykład.
 #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; } 

Wyjście

Wyliczenie w C
  • Jeśli nie podamy żadnej wartości do nazw wyliczeniowych, kompilator automatycznie przypisze do nazw wyliczeniowych wartości domyślne, zaczynając od 0.
  • Możemy także podać wartości do nazwy wyliczeniowej w dowolnej kolejności, a nieprzypisane nazwy otrzymają wartość domyślną, taką jak poprzednia plus jeden.
  • Wartości przypisane do nazw wyliczeniowych muszą być stałymi całkowitymi, tj. nie powinny należeć do innych typów, takich jak string, float itp.
  • Wszystkie nazwy wyliczeń muszą być unikalne w swoim zakresie, tj. jeśli zdefiniujemy dwa wyliczenia o tym samym zakresie, to te dwa wyliczenia powinny mieć różne nazwy wyliczeń, w przeciwnym razie kompilator zgłosi błąd.

Rozumiemy ten scenariusz na przykładzie.

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

Wyjście

Wyliczenie w C
  • W wyliczeniu możemy zdefiniować wyliczeniowy typ danych również bez nazwy.
 #include enum {success, fail} status; int main(void) { status=success; printf(&apos;The value of status is %d&apos;, status); return 0; } 

Wyjście

Wyliczenie w C

Enum a makro w C

  • Makra można również użyć do zdefiniowania stałych nazw, ale w przypadku wyliczenia wszystkie stałe nazw można zgrupować w jednej instrukcji.
    Na przykład,
    # zdefiniuj przejście 0;
    # zdefiniuj sukces 1;
    Powyższe dwie instrukcje można zapisać w jednej instrukcji, używając typu wyliczeniowego.
    stan wyliczeniowy{powodzenie, sukces};
  • Typ wyliczeniowy jest zgodny z regułami zakresu, podczas gdy makro nie przestrzega reguł zakresu.
  • W Enum, jeśli nie przypiszemy wartości do nazw wyliczeniowych, kompilator automatycznie przypisze do nazw wyliczeniowych wartość domyślną. Jednak w przypadku makra wartości muszą być jawnie przypisane.
  • Typ wyliczenia w C jest liczbą całkowitą, ale typ makra może być dowolnego typu.