Ashish Rawat
Ashish Rawat

Reputation: 3513

Can we use multiple constants with different enums tags in C

I have following code:

enum tag1 {
 n1, n2, n3
};

enum tag2 {
 n4, n5, n1
};

Now, I got an error, n1 are used two times

So my question is what is the use of enum tags when enum constants doesn't have a scope.

Upvotes: 0

Views: 107

Answers (2)

Vikram Singh
Vikram Singh

Reputation: 958

No, you cannot use it like this. Enums in "C" are not strongly typed.

Using enums increase the level of abstraction and lets the programmer think about what the values mean rather than worry about how they are stored and accessed. This reduces the occurrence of bugs.

Enums have these benefits:

  • They restrict the values that the enum variable can take
  • They force you to think about all the possible values that the enum can take.
  • They are a constant rather than a number, increasing readability of the source code

Upvotes: 3

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726539

You can use enum tags to declare variables of type of the corresponding enum without using a typedef:

enum tag1 varName = n5;

Unfortunately, there is no way to have several enums sharing a member in the same translation unit. Obviously, you can define your two enums in different headers, and make full use of them, as long as the two headers are not included in the same C file.

Upvotes: 1

Related Questions