The #x
is fine because x
is a macro argument.
But, #MAX_NAME_LEN
is not fine because MAX_NAME_LEN
is not a macro argument
You can fix this with an extra "helper" macro:
#define MAX_NAME_LEN 15
#define STRINGIFY(s) \
#s
#define PRINT_CELL(x) \
printf("|%" STRINGIFY(MAX_NAME_LEN) "s|", #x);
That solves the complaint from cpp
, but the result compiles with an error because the output produces a complaint about the format string for printf
:
int
main(void)
{
printf("|%" "MAX_NAME_LEN" "s|" "hello");
return 0;
}
To solve that, change: %
to %%
:
#include <stdio.h>
#define MAX_NAME_LEN 15
#define STRINGIFY(s) \
#s
#define PRINT_CELL(x) \
printf("|%%" STRINGIFY(MAX_NAME_LEN) "s|" #x "\n");
int
main(void)
{
PRINT_CELL(hello)
return 0;
}
But, when we run that version, the output of program is:
|%MAX_NAME_LENs|hello
What I suspect you're trying to do can be accomplished better using the *
modifier of %s
:
#include <stdio.h>
#define MAX_NAME_LEN 15
#define STRINGIFY(s) \
#s
#define PRINT_CELL(x) \
printf("|%*s\n",MAX_NAME_LEN,#x);
int
main(void)
{
PRINT_CELL(hello)
return 0;
}
The output of this is:
| hello