Saturday, May 22, 2010

C++ returning enumeration from function?

How do i go about returning an enumeration from a function?





via global pointer?





i.e





int myFunction()


{


if(x=1)


{


enum value {val1 = 1, val2 = 2}


}


else


{


enum value {val1 = 2, val2 = 3}


}


}





How would I go about passing the enum back to the main function? Thanks!

C++ returning enumeration from function?
enum is not a type by itself, it's a type category. A variable can't be of type enum, it could only be of a specific enum type.





So, your syntax is not valid.


Here is an example:





enum TypeColor


{ RED, BLUE, GREEN, OTHER};





TypeColor GetColor(char* in_colorName)


{


TypeColor VarColor = OTHER;


if (stricmp(in_colorName, "red" == 0))


VarColor = RED


else if (stricmp(in_colorName, "blue" == 0))


VarColor = BLUE


else if (stricmp(in_colorName, "green" == 0))


VarColor = GREEN;


return VarColor;


}





int main()


{


TypeColor myColor = GetColor("green");


}
Reply:Check this out... maybe it will help.





http://www.thescripts.com/forum/thread68...
Reply:When you declare an enumeration, it's like you are declaring a new data type. The caller of the function must have access to the declaration, and the funciton itself needs access to it. In your example, you'd probably declare it globally, before any code needs to use it. Don't declare the enum inside a function.





Here's a rewrite of your code.





//First, declare and define the enum:





enum value {val1 = 1, val2 = 2};





value myFunction(int x) //function returns type 'value'


{


value retval;





if (x == 1) //DOUBLE equals here!!


{


retval = val1;


}


else if (x == 2)


{


retval = val2;


}





//TODO: decide what you want to do if it's neither!!





return retval;


}





The calling code would look like this:





value val = MyFunction(1);


No comments:

Post a Comment