You can, but I think it might be better to use the capability printf()
has to specify the field size and/or precision dynamically:
#include <stdio.h>
int main(int argc, char* argv[])
{
// specify the field size dynamically
printf( ":%*s:\n", 10, "*");
printf( ":%*s:\n", 15, "*");
// specify the precision dynamically
printf( "%.*s\n", 10, "******************************************");
printf( "%.*s\n", 15, "******************************************");
return 0;
}
This has the advantage of not using the preprocessor and also will let you use variables or functions to specify the field width instead of literals.
If you do decide to use macros instead, please use the #
operator indirectly (and the ##
operator if you use it elsewhere) like so:
// macros to allow safer use of the # and ## operators
#ifndef STRINGIFY
#define STRINGIFY2( x) #x
#define STRINGIFY(x) STRINGIFY2(x)
#endif
#define STR_FMTB(x) "%" STRINGIFY(x) "s"
Otherwise if you decide to use macros to specify the field width, you'll get undesired behavior (as described in http://stackoverflow.com/questions/216875/in-macros/217181#217181).