简体   繁体   中英

Compiler #warning: print enum value

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.

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 .)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM