Sau*_*rma 3 c++ macros gcc c++11
我需要一些关于这个C++代码如何表现和返回值的解释
#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;
}
Run Code Online (Sandbox Code Playgroud)
到目前为止我关注的是#n返回参数的数量MY_MACRO(n)但是如果之前SQR(100)它将被替换为100 * 100(如果我们计算空格则为9个字符)但是现在sizeof(9)应该打印4但是它返回9cout<< sizeof(MY_MACRO(SQR(100)))<<endl;
它的背后是什么?
宏替换后,您的代码将转换为
sizeof("SQR(100)");
这将给出9作为字符串文字的大小,包括终止'\0'.
#n 将参数设为字符串,而不是参数的数量
例如 :
#define display( n ) printf( "Result" #n " = %d", Result##n )
int Result99 = 78;
display( 99 ) ; // Will output -> Result99 = 78
Run Code Online (Sandbox Code Playgroud)