Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Redeclare variable inside enum

In C, If we re-declare variable inside enum, then compiler gives an error that "'i' redeclared as different kind of symbol".It Ok.

#include <stdio.h>

int i = 10;

struct S 
{ 
    enum 
    {
        i = 20
    }e; 
};

int main()
{
    printf("%d\n", i);
}

But, In C++, If we redeclare variable inside enum, then it's working fine.

#include <iostream>
using namespace std;

int i = 10;

struct S 
{ 
    enum 
    {
        i = 20
    }e; 
};

int main()
{
    cout<<i<<endl;
}

I don't understand, Why doesn't C++ compiler gives an error for redeclaration variable?

like image 462
msc Avatar asked Jan 10 '18 07:01

msc


People also ask

Can we declare variable in enum?

Enumerations are similar to classes and, you can have variables, methods, and constructors within them.

Can you have methods in an enum?

The enum class body can include methods and other fields. The compiler automatically adds some special methods when it creates an enum. For example, they have a static values method that returns an array containing all of the values of the enum in the order they are declared.

Can we have enum inside enum in C?

It is not possible to have enum of enums, but you could represent your data by having the type and cause separately either as part of a struct or allocating certain bits for each of the fields.

Can enum be final?

An enum can't be final, because the compiler will generate subclasses for each enum entry that the programmer has explicitly defined an implementation for. Moreover, an enum where no instances have their own class body is implicitly final, by JLS section 8.9.


1 Answers

It doesn't give a re-declaration error because the enumerator is introduced into class scope. Recall that a struct and class are mostly interchangeable in C++. The scope of S contains the enumerator i.

In C however, struct S doesn't define a scope. There are only 4 types of scope in C: function, file, block, and function prototype. As such, i is introduced into file scope where the variable i is already defined.

like image 94
StoryTeller - Unslander Monica Avatar answered Sep 27 '22 22:09

StoryTeller - Unslander Monica