Quantcast
Channel: interview Question – wikistack
Viewing all articles
Browse latest Browse all 34

How enum in c is different from enum in c++?

$
0
0

In this blog we will learn how enum in c is different from enum in c++.

In C enums are created as below

#include<stdio.h>

enum DAY
{
    MON, TUE, WED, THU, FRI, SAT, SUN
};

enum DAY day;

int main()
{
    return 0;
}

while in c++ enums are created as

#include<stdio.h>

enum DAY
{
    MON, TUE, WED, THU, FRI, SAT, SUN
};

DAY day;

int main()
{
    return 0;
}

So In C++, an instance of the enum DAY can be defined and declared without declaring its type, while in C to create an instance of enum we need enum keyword prefix e.g enum DAY day.

Let us create a main.c file with the below code and try to compile.

#include<stdio.h>

enum DAY
{
    MON, TUE, WED, THU, FRI, SAT, SUN
};

DAY day;

int main()
{
    return 0;
}

#gcc main.c

main.c:8:1: error: unknown type name ‘DAY’
 DAY day;
 ^

So in C , we need to prefix enum keyword before DAY day , like enum DAY day. We can also use typedef keyword in c , so that it would be possible to instantiate enum DAY like DAY day. Let us see example.

#include<stdio.h>

typedef enum DAY_
{
    MON, TUE, WED, THU, FRI, SAT, SUN
} DAY;

DAY day;

int main()
{
    return 0;
}

Type safety difference

In c++ enum is type safe while in enum in c is not type safe. Let us see meaning of type safety. Following example in c would work while in c++ it will error out.

How enum in c is different from enum in c++

The post How enum in c is different from enum in c++? appeared first on wikistack.


Viewing all articles
Browse latest Browse all 34

Trending Articles