Reputation: 2462
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?
Upvotes: 3
Views: 170
Reputation: 47794
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
Upvotes: 5
Reputation: 54325
You are not using the right definition of #n
. It is not the number of arguments. It makes it into a string.
Upvotes: 5