0

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?

Aravind Ekan
  • 27
  • 1
  • 6

2 Answers2

1

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.

teapot418
  • 1,239
  • 1
  • 3
  • 9
1

The preprocessor will replace SET_ENUM(rs, a) with rs = a.

So you'll need to add the cast so that it is replaced by rs = (reasons)a.

If you are only setting that enum you could just define the macro as:

#define SET_ENUM(dest, data) dest = (reasons)data;

If you want it to be for other enums, I'm afraid you'll have to add the enum as parameter to the macro:

#define SET_ENUM(dest, data, T) dest = (T)data;

And then call it like this:

SET_ENUM(rs, a, reason);
Andrés Alcarraz
  • 1,570
  • 1
  • 12
  • 21