Reputation: 650
I want to print the value of an enumeration as a #warning
or as a #pragma message
. I use typedef enum
instead of #define
'ing values, as it makes editing easier and allows for typing function parameters and return values.
Reason for printing: The enum
's constant max value must not exceed a certain value, however I can't check the value directly in the code, as its values are auto incremented: typedef enum {a, b, ... az } mytype_t;
. In this example, az must be smaller than [any u_int].
I have tried to stringify the value according to this post, however it works only for #define
'd values. I tried variations on the enum
value, but I could not get the actual value to print, only its name.
Is there a way to print an enum value (or also a const variable) when compiling? Thanks.
EDIT: I use Microchips XC8 compiler (8 bit) and C99.
Upvotes: 0
Views: 935
Reputation: 222486
The C standard does not provide for a way to report the values of enumeration constants in preprocessor macros or other compile-time methods. However, it is possible to test that the value is within a desired range.
As of C 2011, you can use _Static_assert
to test enumeration constants:
enum { a, b, c, d, e };
_Static_assert(e <= 3, "Enumeration constant exceeds 3.");
Before C 2011, you can kludge tests in various ways, such as:
enum { a, b, c, d, e };
int FailIfSizeMismatches[1]; // Define array with good size.
int FailIfSizeMismatches[e <= 3]; // Define with conflicting size if test fails.
(In C++, replace _Static_assert
with static_assert
.)
Upvotes: 1
Reputation: 1
As the comment Frankie_C written, you have to classify preprocessing and processing. enum is evaluated after preprocessing while #define, #pragma, #warning is evaluated on preprocessing
Upvotes: 0