C enum (or enumeration)

enum is a keyword of c programming language that are used to define multiple constant integer variables. this group of variables is data member of enum. that is also called enumeration.

Enumeration

there is defined by using of this following syntax.

enum tag_name{
  constant_variable1;
  constant_variable2;
  constant_variable2;
  :
  :
} variable_list;
Iteam overview
enum keyword
tag_name Name of enum
constant_variables list of integer constant variables
variable_list enum variable list

Example:

/* 
  Example of enum in c
*/
/*Header file*/
#include <stdio.h>
//define enum wallet
enum wallet{
  coin=5,
  rupee=800,
  dollar=10,
};
int main(){
    //print enum variable value
    printf(" coins: %d\n",coin ); 
    printf(" rupee: %d\n",rupee );  
    printf(" dollar: %d\n",dollar );  
  return 0;
}

Output

coins: 5
rupee: 800
dollar: 10

Behavior of enumeration

1) Enumeration data member are contain constant value of integers.if programmer are not provide any value to enumeration data member then it will gets default value. default value of enumeration is started by zero. In similar way if there are not provide value of intermediate data member then that are inherited the values of previously defined variable.

And increments it's value by one. and stored that value to variable memory location.

/* 
  Example of enum default value
*/
/*Header file*/
#include <stdio.h>
//define enum Booklist
enum Booklist{
  c,cpp,java,python
};

int main(){
  //defalu value of enum Booklist
    printf(" c      : %d\n", c);
    printf(" cpp    : %d\n", cpp);
    printf(" java   : %d\n", java);
    printf(" python : %d\n", python);
    return 0;
}

Output

 c      : 0
 cpp    : 1
 java   : 2
 python : 3 

2) We can provide data value in any order.if we are missing to not given value of any variables. then they are get those value on our left hand side. but this value get in increment by one. look at view this example.

/* 
  Example of enum default value
*/
/*Header file*/
#include <stdio.h>
//define enum alphabet
enum alphabet{
  A=10,
  B,
  C,
  D=30,
  E,
  F,
  G=40,
  H
};

int main(){
    //print values
  printf("A %d\n", A);
  printf("B %d\n", B);
  printf("C %d\n", C);
  printf("D %d\n", D);
  printf("E %d\n", E);
  printf("F %d\n", F);
  printf("G %d\n", G);
  printf("H %d\n", H );

    return 0;
}

Output

A 10
B 11
C 12
D 30
E 31
F 32
G 40
H 41

3) enumeration constant variable are unique in their scope. for example

enum student{
  id,
  marks
};
enum employee{
  id,//same variable in student
  age
};

int main(){
    return 0;
}

Produce error

redeclaration of enumerator ‘id’


Please share your knowledge to improve code and content standard. Also submit your doubts, and test case. We improve by your feedback. We will try to resolve your query as soon as possible.

New Comment







© 2021, kalkicode.com, All rights reserved