今天,我听说 C++ 程序员可以通过 #define
关键字来完成一些魔鬼般的事情。例如,
#define private public
#define class struct
#define sizeof(x) (sizeof(x) - 1)
#define true (__LINE__ % 2)
#define pthread_mutex_lock(m) 0
我对函数定义
感兴趣。所以我尝试通过
CRITICAL_SECTION g_critSec;
#define InitializeCriticalSection(n, y) 0
void comparemutexwithcriticalsection() {
InitializeCriticalSection(&g_critSec);
std::cout << "Iterations: " << g_cRepeatCount << "\n\r";
// other codes...
}
在VS2013下可以编译成功,下面是反汇编代码。
void comparemutexwithcriticalsection() {
00F9A710 push ebp
00F9A711 mov ebp,esp
00F9A713 sub esp,0CCh
00F9A719 push ebx
00F9A71A push esi
00F9A71B push edi
00F9A71C lea edi,[ebp-0CCh]
00F9A722 mov ecx,33h
00F9A727 mov eax,0CCCCCCCCh
00F9A72C rep stos dword ptr es:[edi]
InitializeCriticalSection(&g_critSec);
std::cout << "Iterations: " << g_cRepeatCount << "\n\r";
00F9A72E push 0FB66F4h
InitializeCriticalSection(&g_critSec);
似乎在 #define
宏中忽略了参数,对吗?
基于以上,我尝试定义
我自己的函数为0
#define myfunc(a) 0
void myfunc(int a)
{
cout << a << endl;
}
但是在VS2013下编译失败。 有人可以帮我找出这里遗漏的东西吗?还是我的想法有问题?
最佳答案
首先让我们非常清楚,重新定义语言关键字如 private
是未定义的,并且可能以多种方式表现。
然后,关于您的函数,问题在于您在定义函数之前创建了#define
。以这种方式尝试:
void myfunc(int a)
{
cout << a << endl;
}
#define myfunc(a) 0
如果你按照你最初提议的方式去做,你会在预处理后得到这个结果,而这显然是非法的:
void 0(int a)
{
cout << a << endl;
}
关于c++ - 忽略使用函数名称定义宏的参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33535896/