I am working on a big project in which I need to use a generic macro to assign my values from a big payload. the values may be int, uint, bool or enum. all other macros are working fine only for the enum I need help with. Consider this piece of code as something I want to achieve.
#include <stdio.h>
enum reasons { REASON1 = 1, REASON2 = 2, MAX_REASON = 3 };
#define SET_ENUM(dest, data) dest = data;
int main(void)
{
int a = 2;
enum reasons rs;
SET_ENUM(rs, a);
printf("REASON is -> %d\n", rs);
return 0;
}
Here it works everything fine but in my Coverity run it shows
Event mixed_enum_type: enumerated type mixed with another type
I want to typecast the data to the dest but need to do it from the macro. Any suggestions?
You could do a three-arg SET_ENUM, specifying the type:
#define SET_ENUM(dest, type, data) dest = (enum type) data
...
SET_ENUM(rs, reasons, a);
Or with certain compilers (gcc) you could use the typeof
keyword:
#define SET_ENUM(dest, data) dest = (typeof(dest)) data
...
SET_ENUM(rs, a);
The typeof
keyword is currently a non-standard extension, it seems to be planned for the C23 standard.