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?
Enumerations are similar to classes and, you can have variables, methods, and constructors within them.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With