Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does C compiler treat enum?

Tags:

c

enums

enum is a user-defined type. In general there are no big differences between enum in C and C++. Except for scopes in C++: if some enum is declared within function or class it cannot be accessed outside of declared function/class. This is not applicable to C.

There is no difference in declaration. For example, it is possible to declare new enum as follows (for both C and C++):

enum newEnum { zero = 0, one, two, three };

There is almost no difference in defining new variables. To define new variable with new defined type it is possible to use the following line:

enum newEnum varA = zero; // though allowed to skip enum keyword in C++

But there is one interesting point. In C++ you cannot add two enum values and assign the result to enum-type variable:

varA = one + zero; // won't compile in c++

It is explainable: enum values can be casted to int values, but not vice versa (int to enum). So in the last example a compiler cannot assign the result of sum (with type of int) to varA (enum newEnum), because it cannot covert int to newEnum.

However it is possible in C: the last code line successfully compiles. This confuses me. Therefore a question rises: how does C compiler treat enum? Is it not even a custom type for it? Is it just int?

like image 249
newbieboi Avatar asked Oct 30 '25 12:10

newbieboi


1 Answers

In C the enumeration constants (i.e. the values zero, one, two, three) have type int.

The type enum newEnum also exists, but the enumerators do not have that type. The type enum newEnum is an integer type, and the compiler can choose the size of the type, but it must be at least large enough to hold all of the defined enumerators. In your example its size might be 1, 2, 4, 8, or anything else.

There can be variables and values of the enumerated type, e.g. enum newEnum x = 3; ++x;.

The enumerated type participates in implicit integer conversions with a rank according to its size .

like image 157
M.M Avatar answered Nov 01 '25 02:11

M.M