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.
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 " ")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With