Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pad strings using preprocessor macros

Is it possible to pad a string with spaces (or any character) using only preprocessor macros? If so, how?

Example:

#define SOME_STR               "v1.1"
#define STR_PAD(str, len)      // <-- padding defined string

#define SOME_STR_PADDED        STR_PAD(SOME_STR, 10)        // evaluates to "v1.1      "

I know that there are simple solutions during runtime, but my question is how to pad a string during compile time.

like image 292
MemAllox Avatar asked Sep 18 '25 08:09

MemAllox


1 Answers

Very interesting question! It does not seem possible in the general case where both str and len are unknown, and also when str alone is unknown. If both the length of str is known and len is bounded by some reasonable fixed value, one could generate a compound ternary expression that compiles to a single string constant.

Here is an illustration:

// compile time padding: str must be a string constant and len <= 4 + strlen(str)
#define STR_PAD(str, len)  (((len) + 1 <= sizeof str) ? str :        \
                            ((len) == sizeof str) ? str " " :        \
                            ((len) == sizeof str + 1) ? str "  " :   \
                            ((len) == sizeof str + 2) ? str "   " :  \
                            str "    ")
like image 53
chqrlie Avatar answered Sep 20 '25 00:09

chqrlie