When using C3 in an expression, the compiler can't tell which C3 it is. But in my program, such a case happens with function parameters: a function has a parameter of type E1. So my question is: does C++ allow passing C3 as a parameter to the function? It doesn't look like a problem to me because the compiler knows the type is E1, which has only one constant names C3, so there's shouldn't be a problem. But still, I can't be sure...so that's why I'm asking. Also, enums are MEANT to limit the acceptable values, so it makes sense not to accept E2's C3 as a parameter. Right?
Edit: Also, is it legal to compare an enum and a constant without error? Example:
1 2 3
voinf f1(E1 e)
{
if (e == C3)
The compiler can tell it's E1's C3, not E2's... but is this legal in C++?
enum E1 { C1=45, C2=453, C3=77};
//Error - this second enum is at the same scope as E1
//and contains a value of the same name C3
enum E2 { C3=36, C4=73, C5=384 };
class MyClass
{
//This enum is in a different scope from E1 - so C3 here is ok
public:
enum E3 {C3=36, C4=73, C5=384};
};
//A function taking parameter of type enum E1
// The parameter name of C3 is ok - because it in in the scope
//of the function - not in same scope as E1
void func(E1 C3)
{
//You may get a warning from the compiler here
//about the C3 name clash
enum E6 { C1, C2, C3};
}
int main()
{
E1 enum_var1 = C2; //OK
MyClass::E3 enum_var2 = C3;//Error- these are from different enums
MyClass::E3 enum_var3 = MyClass::C3; //OK
func (77);//Error - No implicit(compiler supplied) conversion from int to enum
int x = C3; //OK to convert from enum to int.
if (x == C1);//OK to compare int and enum
if (C1 > x);//OK as above
if (C1 ==C2); //OK both values of type E1.
if (C1 == MyClass::C3); //This may get a warning depending on your compiler
func(C3); // OK - this is the C3 from the enum E1 in global scope.
func(::C3);//Same as previous line - just using the scope resolution operator
func(enum_var1); //OK
func(enum_var3);//Error - enum_var3 is of type MyClass::E3 - not E1 as needed by the function
return 0;
}