tags:

views:

141

answers:

3
+2  Q: 

Use of enums in C?

Hi all, Is there anyway by which we can copy one enum to another one?For eg:

     enum Element4_Range{a4=1,b4,c4,d4};
     enum Element3_Range{a3=1,b3,c3};
     enum Element3_Range Myarr3[10];
     enum Element4_Range Myarr4[10];

     enum Element3_Range MyFunc(Element4_Range);

     main()
     {
          MyFunc(Myarr4);
     }
     enum Element3_Range MyFunc(Element4_Range Target)
     {
           enum Element3_Range Source;
           Source = Target;-----------Is this possible?
      }

If not can anyone please show me the way to copy the values of enum from one to another?

I was getting an error while executing this like

  1. incompatible types in assignment of Element3_Range*' toElement3_Range[10]'
  2. cannot convert Element4_Range' toElement3_Range' in assignment

Thanks and regards
Maddy

+2  A: 

Cast it:

Source = (Element3_Range)Target;
Jim Buck
@Jim---I had tried that,bnut that didnt work out.The error jst sprang up that 1)conversion from `enum Element4_Range*' to `enum Element3_Range'
maddy
@maddy: Based on that error, you're trying to cast a pointer to an enum to an enum. You must have pasted the wrong code into this question. Is Target a pointer? Is Source? An enum is an integral value and you should be able to cast it.
tomlogic
@maddy are you running a compiler in C++ mode? for example, does your source file end with .cpp (rather than .c) and you are using gcc? You shouldn't see the error you report when using the suggested cast in C. Also, casting enums is not recommended -- although as you will see, it is possible. ;)
Heath Hunnicutt
@Health..Yes i am running a c++ compiler.But I had jst tried using memcpy(Source,Target,10);which i guess worked fine.Any suggestion on this plz
maddy
@Maddy. No 'l' in my name... Regardless of whether you are able to call memcpy(), using a C++ compiler will affect your ability to use casts. Most C++ compilers have a C mode for compiling C. Which compiler are you using, and what is the extension of your source code file?
Heath Hunnicutt
@maddy - please cut and paste the error verbatim. You should be able to cast an enum from one to another. It's not a great practice, but it should work. Try this one too: `Source = (Element3_Range)(int)Target;`
Jim Buck
+1  A: 

An enum is an int with type checking. If you do not want the type checking, use int.

drawnonward
A: 

You might also consider using a switch block:

switch(Target) {
case a4:
  return a3;
case b4:
  return b3;
case c4:
  return c3;
}

It may not always be desired to use the "actual value" of an enum, as opposed to its "logical value". Of course, this isn't fast, but that's not the point.

Ioan