Related Articles

Related Articles

Write a C macro PRINT(x) which prints x
  • Difficulty Level : Easy
  • Last Updated : 28 May, 2017

At the first look, it seems that writing a C macro which prints its argument is child’s play. Following program should work i.e. it should print x

filter_none

edit
close

play_arrow

link
brightness_4
code

#define PRINT(x) (x)
int main()
  printf("%s",PRINT(x));
  return 0;
}

chevron_right


But it would issue compile error because the data type of x, which is taken as variable by the compiler, is unknown. Now it doesn’t look so obvious. Isn’t it? Guess what, the followings also won’t work

filter_none

edit
close

play_arrow

link
brightness_4
code

#define PRINT(x) ('x')
#define PRINT(x) ("x")

chevron_right


But if we know one of lesser known traits of C language, writing such a macro is really a child’s play. 🙂 In C, there’s a # directive, also called ‘Stringizing Operator’, which does this magic. Basically # directive converts its argument in a string. Voila! it is so simple to do the rest. So the above program can be modified as below.

filter_none

edit
close

play_arrow

link
brightness_4
code

#define PRINT(x) (#x)
int main()
  printf("%s",PRINT(x));
  return 0;
}

chevron_right


Now if the input is PRINT(x), it would print x. In fact, if the input is PRINT(geeks), it would print geeks.

You may find the details of this directive from Microsoft portal here.

Attention reader! Don’t stop learning now. Get hold of all the important C++ Foundation and STL concepts with the C++ Foundation and STL courses at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up
Recommended Articles
Page :