Extracting the number of digits in a macro constant at compile time
I need to do some preprocessor magic. Suppose I have a global constant
#define MAX_VALUE 99999
I need to do to extract the length of this constant in its decimal representation at compile time. In other words, I don't want to have another constant
#define MAX_VALUE_STRLEN 5
pollution of the global namespace and I don't want to add space to the code that needs to be changed if MAX_VALUE changes. If I have a numeric letter then I can do something like
#define INTLEN(x) (sizeof(#x)/sizeof((#x)[0]) - 1)
and INTLEN(99999)
will then expand to 5
at compile time. Unfortunately, I cannot do something like
INTLEN(MAX_VALUE),
because the preprocessor expands INTLEN first, so I get
(sizeof("MAX_VALUE")/sizeof(("MAX_VALUE")[0]) - 1)
Is there a preprocessor trick that achieves what I want? Another harder issue that I must safely ignore is that it can be made general enough, if someone decides to add an annotation like, say, 99999L to a constant, that I can still get the correct value?
source to share