Question

I need a little explanation over how this C++ code is behaving and returning value

#include<iostream>
using namespace std;
#define MY_MACRO(n) #n
#define SQR(x) x * x
int main()
{
    //cout<<MY_MACRO(SQR(100))<<endl;
    //cout<< sizeof(SQR(100))<<endl;
    cout<< sizeof(MY_MACRO(SQR(100)))<<endl;

    return 0;
}

As far i am concerned #n returns the number of arguments in the MY_MACRO(n) But if before that SQR(100) will be replaced by 100 * 100 (9 characters if we count spaces) But now sizeof(9) should print 4 but Its returning 9 with cout<< sizeof(MY_MACRO(SQR(100)))<<endl;

What's the catch behind it?

Was it helpful?

Solution

You are not using the right definition of #n. It is not the number of arguments. It makes it into a string.

OTHER TIPS

After macro substitution your code will be converted to

sizeof("SQR(100)");

which will give 9 as size of string literal including the terminating '\0'.

#n will make the argument as string, its not the number of argument

For example :

#define display( n ) printf( "Result" #n " = %d", Result##n )
int Result99 = 78;

display( 99 ) ; // Will output -> Result99 = 78
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top