Please explain the working of the program, how is the function call is going on and what's the use of #var(how it works).
#include <stdio.h>
#define getName(var) #var
int main()
{
printf("%s", getName( char ));
return 0;
}
Please explain the working of the program, how is the function call is going on and what's the use of #var(how it works).
#include <stdio.h>
#define getName(var) #var
int main()
{
printf("%s", getName( char ));
return 0;
}
#
is an operator in preprocessing macro replacement that converts a parameter to a string literal.
So, when getName
is invoked with the argument char
, #var
is replaced with a string literal containing the tokens for var
, which is just the single token char
. So the replacement is the string literal "char"
.
The result in the printf
statement is printf("%s", "char");
, which prints “char”.
If you compile it with -E
compile option using gcc
the answer is quite obvious. Below is the preprocessed program:
int main()
{
printf("%s", "char");
return 0;
}
As you can see the #
macro makes a C string literal from the parameter.
Here you have another example
#include <stdio.h>
#define result(expr) printf("%s = %d\n", #expr, expr)
int main()
{
result(5+5);
return 0;
}
It will print
5+5 = 10