logo

C'de numaralandırma

C'deki numaralandırma aynı zamanda numaralandırılmış tür olarak da bilinir. Tamsayı değerlerden oluşan, kullanıcı tanımlı bir veri türüdür ve bu değerlere anlamlı adlar verir. C'de enum kullanımı programın anlaşılmasını ve bakımını kolaylaştırır. Enum, enum anahtar sözcüğü kullanılarak tanımlanır.

C'de numaralandırmayı tanımlamanın yolu aşağıdadır:

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

Yukarıdaki bildirimde 'N' tamsayı sabitini içeren flag olarak adlandırılan enum'u tanımladık. integer_const1'in varsayılan değeri 0'dır, integer_const2 1'dir vb. Tamsayı sabitlerinin bildirim sırasındaki varsayılan değerini de değiştirebiliriz.

Örneğin:

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

Mangonun varsayılan değeri 0, elma 1, çilek 2 ve papayanın varsayılan değeri 3'tür. Bu varsayılan değerleri değiştirmek istersek aşağıdaki işlemleri yapabiliriz:

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

Numaralandırılmış tür bildirimi

Bildiğimiz gibi, C dilinde int, float, char vb. gibi önceden tanımlanmış bir türün değişkenini bildirmemiz gerekir. Benzer şekilde, enum gibi kullanıcı tanımlı bir veri türünün değişkenini de bildirebiliriz. Bir enum türünün değişkenini nasıl bildirebileceğimizi görelim.

Aşağıda gösterildiği gibi tür durumunun numaralandırmasını oluşturduğumuzu varsayalım:

 enum status{false,true}; 

Şimdi durum tipinin değişkenini oluşturuyoruz:

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

Yukarıdaki ifadede type status değişkeninin 's' değişkenini deklare ettik.

Bir değişken oluşturmak için yukarıdaki iki ifade şu şekilde yazılabilir:

 enum status{false,true} s; 

Bu durumda false'un varsayılan değeri 0'a, true'nun değeri ise 1'e eşit olacaktır.

Basit bir enum programı oluşturalım.

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

Yukarıdaki kodda hafta içi olarak adlandırılan bir enum türü oluşturuyoruz ve bu, yedi günün tamamının adını içeriyor. Pazar gününe 1 değer atadık, diğer tüm isimlere bir önceki değerin bir fazlası kadar değer verilecektir.

Çıktı

C'de numaralandırma

Numaralandırmanın daha net anlaşılabilmesi için bir örnek daha verelim.

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

Çıktı

C'de numaralandırma

Enum ile ilgili bazı önemli noktalar

  • Bir numaralandırma türünde kullanılabilen numaralandırma adları aynı değere sahip olabilir. Örneğe bakalım.
 #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; } 

Çıktı

C'de numaralandırma
  • Enum adlarına herhangi bir değer vermezsek derleyici otomatik olarak 0'dan başlayarak enum adlarına varsayılan değerleri atayacaktır.
  • Enum ismine de değerleri herhangi bir sırayla verebiliriz ve atanmamış isimler bir önceki artı bir olarak varsayılan değeri alacaktır.
  • Enum adlarına atanan değerler integral sabit olmalıdır, yani string, float vb. diğer türlerde olmamalıdır.
  • Tüm numaralandırma adlarının kapsamları açısından benzersiz olması gerekir, yani aynı kapsama sahip iki numaralandırma tanımlarsak, bu iki numaralandırmanın farklı numaralandırma adlarına sahip olması gerekir, aksi takdirde derleyici hata verecektir.

Bu senaryoyu bir örnek üzerinden anlayalım.

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

Çıktı

C'de numaralandırma
  • Numaralandırmada, numaralandırılmış bir veri türünü isim olmadan da tanımlayabiliriz.
 #include enum {success, fail} status; int main(void) { status=success; printf(&apos;The value of status is %d&apos;, status); return 0; } 

Çıktı

C'de numaralandırma

C'de Enum ve Makro

  • Makro aynı zamanda ad sabitlerini tanımlamak için de kullanılabilir, ancak bir numaralandırma durumunda tüm ad sabitleri tek bir ifadede birlikte gruplandırılabilir.
    Örneğin,
    # geçiş 0'ı tanımlayın;
    # başarıyı tanımlayın 1;
    Yukarıdaki iki ifade enum tipi kullanılarak tek bir ifadede yazılabilir.
    enum durumu{geçti, başarı};
  • Enum türü kapsam kurallarına uyarken makro kapsam kurallarına uymaz.
  • Enum'da değerleri enum adlarına atamazsak, derleyici otomatik olarak enum adlarına varsayılan değeri atayacaktır. Ancak makro durumunda değerlerin açıkça atanması gerekir.
  • C'deki enum türü bir tam sayıdır, ancak makro türü herhangi bir türde olabilir.