-3

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; 
}
Srijoy_paul
  • 77
  • 1
  • 6

2 Answers2

3

# 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”.

Eric Postpischil
  • 195,579
  • 13
  • 168
  • 312
3

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

https://godbolt.org/z/Ec8T3T

Suraj Rao
  • 29,388
  • 11
  • 94
  • 103
0___________
  • 60,014
  • 4
  • 34
  • 74