In C programming, an enumeration type (also called enum) is a data type that consists of integral constants. To define enums, the enum keyword is used. enum flag {const1, const2, ..., constN}; By default, const1 is 0, const2 is 1 and so on.
The default value for an enum is zero.
The default value of an enumeration type E is the value produced by expression (E)0 , even if zero doesn't have the corresponding enum member. You use an enumeration type to represent a choice from a set of mutually exclusive values or a combination of choices.
1. Two enum names can have same value. For example, in the following C program both 'Failed' and 'Freezed' have same value 0.
Yes. Unless you specify otherwise in the definition of the enumeration, the initial enumerator always has the value zero and the value of each subsequent enumerator is one greater than the previous enumerator.
C99 Standard
The N1265 C99 draft says at 6.7.2.2/3 "Enumeration specifiers"
An enumerator with = defines its enumeration constant as the value of the constant expression. If the first enumerator has no
=
, the value of its enumeration constant is 0. Each subsequent enumerator with no = defines its enumeration constant as the value of the constant expression obtained by adding 1 to the value of the previous enumeration constant. (The use of enumerators with = may produce enumeration constants with values that duplicate other values in the same enumeration.)
So the following always holds on conforming implementations:
main.c
#include <assert.h>
#include <limits.h>
enum E {
E0,
E1,
E2 = 3,
E3 = 3,
E4,
E5 = INT_MAX,
#if 0
/* error: overflow in enumeration values */
E6,
#endif
};
int main(void) {
/* If unspecified, the first is 0. */
assert(E0 == 0);
assert(E1 == 1);
/* Repeated number, no problem. */
assert(E2 == 3);
assert(E3 == 3);
/* Continue from the last one. */
assert(E4 == 4);
assert(E5 == INT_MAX);
return 0;
}
Compile and run:
gcc -std=c99 -Wall -Wextra -pedantic -o main.out main.c
./main.out
Tested in Ubuntu 16.04, GCC 6.4.0.
If the first value of the enum variable is not initialized then the C compiler automatically assigns the value 0.The compiler keeps on increasing the value of preceeding enum variable by 1.
Eg:
enum months{jan,feb,mar}
Explanation: Value of jan will be 0,feb will be 1,mar will be 2.
enum months{jan=123,feb=999,mar}
Explanation: Value of jan will be 123,feb will be 999,mar will be 1000.
enum months{jan='a',feb='s',mar}
Explanation: Value of jan will be 'a',feb will be 's',mar will be 't'.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With