This code doesn’t work but when I put print(7) this works fine:
#include<stdio.h>
#define print(i) printf("%"#i"c",ch);
int main(void)
{
char ch ='*';
int N;
scanf("%d",&N);
if (N%2 == 0)
{
print(N); // print(7);
}
else
{
}
}
Here is the compilation output
gcc draw.c -o draw
draw.c: In function ‘main’:
draw.c:11: warning: unknown conversion type character ‘N’ in format
How can I get the code to work for a user inserted input. Please help.
The problem is that the
#operator is part of the preprocessor. It doesn’t understand run-time values.The
printffunction recognizes a*syntax that tells it to accept anintargument that specifies a field width, rather than having the width as a constant in the format string.For example, this function could replace your macro. Note that I’ve made
cha parameter; I think it’s much clearer that way.Personally, I probably wouldn’t bother with either a function or a macro for this; I’d just call
printfdirectly: