logo

Aufzählung in C

Die Aufzählung in C wird auch als Aufzählungstyp bezeichnet. Es handelt sich um einen benutzerdefinierten Datentyp, der aus ganzzahligen Werten besteht und diesen Werten aussagekräftige Namen gibt. Durch die Verwendung von enum in C ist das Programm leicht zu verstehen und zu warten. Die Aufzählung wird mithilfe des Schlüsselworts enum definiert.

So definieren Sie die Aufzählung in C:

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

In der obigen Deklaration definieren wir die Enumeration mit dem Namen Flag, die „N“ Ganzzahlkonstanten enthält. Der Standardwert von integer_const1 ist 0, integer_const2 ist 1 und so weiter. Wir können auch den Standardwert der Ganzzahlkonstanten zum Zeitpunkt der Deklaration ändern.

Zum Beispiel:

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

Der Standardwert für Mango ist 0, Apfel ist 1, Erdbeere ist 2 und Papaya ist 3. Wenn wir diese Standardwerte ändern möchten, können wir wie folgt vorgehen:

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

Aufzählungstypdeklaration

Wie wir wissen, müssen wir in der Sprache C die Variable eines vordefinierten Typs wie int, float, char usw. deklarieren. Ebenso können wir die Variable eines benutzerdefinierten Datentyps wie enum deklarieren. Sehen wir uns an, wie wir die Variable eines Aufzählungstyps deklarieren können.

Angenommen, wir erstellen die Aufzählung vom Typ Status wie unten gezeigt:

 enum status{false,true}; 

Jetzt erstellen wir die Variable vom Statustyp:

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

In der obigen Anweisung haben wir die Variable „s“ vom Typ Status deklariert.

Um eine Variable zu erstellen, können die beiden obigen Anweisungen wie folgt geschrieben werden:

 enum status{false,true} s; 

In diesem Fall ist der Standardwert von false gleich 0 und der Wert von true gleich 1.

Lassen Sie uns ein einfaches Enumerationsprogramm erstellen.

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

Im obigen Code erstellen wir einen Aufzählungstyp mit dem Namen „Wochentage“, der die Namen aller sieben Tage enthält. Wir haben dem Sonntag 1 Wert zugewiesen, und allen anderen Namen wird ein Wert zugewiesen, der dem vorherigen Wert plus eins entspricht.

Ausgabe

Aufzählung in C

Lassen Sie uns ein weiteres Beispiel demonstrieren, um die Aufzählung besser zu verstehen.

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

Ausgabe

Aufzählung in C

Einige wichtige Punkte im Zusammenhang mit Enum

  • Die in einem Aufzählungstyp verfügbaren Aufzählungsnamen können denselben Wert haben. Schauen wir uns das Beispiel an.
 #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; } 

Ausgabe

Aufzählung in C
  • Wenn wir den Enum-Namen keinen Wert zuweisen, weist der Compiler den Enum-Namen automatisch die Standardwerte beginnend bei 0 zu.
  • Wir können die Werte für den Enum-Namen auch in beliebiger Reihenfolge bereitstellen, und die nicht zugewiesenen Namen erhalten den Standardwert wie der vorherige plus eins.
  • Die den Enum-Namen zugewiesenen Werte müssen ganzzahlige Konstanten sein, d. h. sie dürfen nicht von anderen Typen wie String, Float usw. sein.
  • Alle Enum-Namen müssen in ihrem Gültigkeitsbereich eindeutig sein. Wenn wir also zwei Enums mit demselben Gültigkeitsbereich definieren, sollten diese beiden Enums unterschiedliche Enum-Namen haben, andernfalls gibt der Compiler einen Fehler aus.

Lassen Sie uns dieses Szenario anhand eines Beispiels verstehen.

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

Ausgabe

Aufzählung in C
  • Bei der Aufzählung können wir einen Aufzählungsdatentyp auch ohne den Namen definieren.
 #include enum {success, fail} status; int main(void) { status=success; printf(&apos;The value of status is %d&apos;, status); return 0; } 

Ausgabe

Aufzählung in C

Enum vs. Makro in C

  • Makros können auch zum Definieren der Namenskonstanten verwendet werden, aber im Falle einer Aufzählung können alle Namenskonstanten in einer einzigen Anweisung zusammengefasst werden.
    Zum Beispiel,
    # pass 0 definieren;
    # Erfolg definieren 1;
    Die beiden oben genannten Anweisungen können mithilfe des Enum-Typs in einer einzigen Anweisung geschrieben werden.
    enum status{pass, success};
  • Der Enum-Typ folgt den Bereichsregeln, während das Makro nicht den Bereichsregeln folgt.
  • Wenn wir in Enum den Enum-Namen keine Werte zuweisen, weist der Compiler den Enum-Namen automatisch den Standardwert zu. Bei Makros müssen die Werte jedoch explizit zugewiesen werden.
  • Der Aufzählungstyp in C ist eine Ganzzahl, der Makrotyp kann jedoch beliebig sein.