C enum (or enumeration)

Enumeration

enum is keyword there is also called enumeration in c language. There can used to create user defined data type. they are consist of integer constant.

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 constant value. if we are not provide any value to enumeration then it compiler are put the default value. this default value are start with zero and increment one by one. for example

/* 
  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’

© 2019, regularcodes.com, All rights reserved