C Programming - C Preprocessor - Discussion


What will be the output of the program?

#define str(x) #x
#define Xstr(x) str(x)
#define oper multiply

int main()
    char *opername = Xstr(oper);
    printf("%s\n", opername);
    return 0;

[A]. Error: in macro substitution
[B]. Error: invalid reference 'x' in macro
[C]. print 'multiply'
[D]. No output

Answer: Option C


The macro #define str(x) #x replaces the symbol 'str(x)' with 'x'.

The macro #define Xstr(x) str(x) replaces the symbol 'Xstr(x)' with 'str(x)'.

The macro #define oper multiply replaces the symbol 'oper' with 'multiply'.

Step 1: char *opername = Xstr(oper); The varible *opername is declared as an pointer to a character type.

=> Xstr(oper); becomes,

=> Xstr(multiply);

=> str(multiply)

=> char *opername = multiply

Step 2: printf("%s\n", opername); It prints the value of variable opername.

Hence the output of the program is "multiply"

Rogerthatrambo said: (Jul 30, 2012)  
#define str(x) #x
//#define Xstr(x) str(x)
#define oper multiply

int main()
char *opername = str(oper);
printf("%s\n", opername);
return 0;

// I got "oper" as output.

Can anyone elaborate ?

Asheesh said: (Feb 25, 2014)  
What is use of # symbol in str(x) #x, answer please?

Abhishek said: (Mar 12, 2014)  

You have missed out 'X'. In place of Xstr(oper) , you have written str(oper).

That's why you are getting output as oper.

Aman said: (May 2, 2014)  
str(multiply) will be replaced with #mutiply, So the output will be #multiply not multiply.

Mandar said: (Nov 2, 2014)  
In given problem no double codes are specified so answer should be an error.

DIA said: (Nov 24, 2015)  

But #define oper multiply still exist, why not got "multiply"?

Ritika said: (Mar 7, 2017)  
Why we don't get #multiply?

Deepak said: (Aug 27, 2017)  
It converts the "x" parameter into a null-terminated string. Whatever is given to "x" when the macro is invoked, the exact value of "x" will be placed into the string.

So, basically, the '#' is used to typecast any input to a string.

Post your comments here:

Name *:

Email   : (optional)

» Your comments will be displayed only after manual approval.