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
?
int
in C . (the enum type still exists, just the enumerators don't have that type)enum
is more like a typedef.