Pass an enum to a function referencing an int

dereferencing type-caraund

I have an enumeration

enum AgentStatus { kSTOPPED = 0, kRUNNING, kIDLE, kNAGENTSTATUS };

      

I need to pass it to an external library function with many overloaded options. I want to pass it to the second argument:

DimService::DimService(const char*, int&);
DimService::DimService(const char*, char*);
...

      

If I cast to (int &) my enum variable, I get the infamous warning:

warning: dereferencing type-punned pointer will break strict-aliasing rules

      

If i do cast to (int) i get this

invalid conversion from ‘int’ to ‘char*’
error:   initializing argument 2 of ‘DimService::DimService(const char*, char*)’

      

What's the correct way?

+3


source to share


2 answers


Bill's answer is technically correct.

1) Another approach

Another way to do this, if you need to get rid of the type enumeration, is to make the int type int.

typedef int MyEnum;
enum
{
    CONST1 = 0,
    etc...
};

      

And then just use it as usual. The compiler won't catch bad value assignments, but since you can mark all declarations as type MyEnum, it should be simple enough to keep track of what's going on, and you can just pass variables somewhere that the int says.

2) Dangerous approach



NEVER DO THIS!

EnumType v = EnumValue_...

MyFunction( *((int*)&v) );

      

OR THAT...

#define MAKE_INT_REF(v) *((int*)&(v))

MyFunction( MAKE_INT_REF(v) );

      

The reason is that the compiler can automatically choose the type to use for the enumeration. It can choose int or choose char. You cannot be sure of different compilers and platforms. Therefore, if you try to rename, you will get uncaught code, as well as very dangerous code, because writing back to such a listing can overwrite other values.

+5


source


If you're having trouble with inline casting, it might be helpful to split it as a separate line:



const AgentStatus enumValue = kRUNNING;
...
int intValue = static_cast<int>(enumValue);
DimService("works now", intValue);

      

+8


source







All Articles