我正在尝试在宏中使用预处理程序指令?这可以/如何实现?
#define HTTP_REQUEST_RETURN_ERROR(error) *errCode = error;
#ifdef DEBUG
LeaveCriticalSection(&debugOutputLock);
#endif
return NULL
Run Code Online (Sandbox Code Playgroud)
谢谢,Jori.
当然,您也可以使用不同的定义定义宏两次:
#if defined DEBUG
#define HTTP_REQUEST_RETURN_ERROR(error) do { *errCode = error;\
LeaveCriticalSection(&debugOutputLock);\
return NULL;\
} while(0)
#else
#define HTTP_REQUEST_RETURN_ERROR(error) do { *errCode = error;\
return NULL;\
} while(0)
#endif
Run Code Online (Sandbox Code Playgroud)
这使得一定要避免(平凡优化的)运行时if该xdazz使用.它还包含典型的宏体do ... while,使其看起来像一个声明.
更新:为了澄清,C中的多语句宏通常在do ... while(0)循环中包装(在宏定义中),因为这会使整个文本成为单个语句.这使得宏的使用可以很好地适用于范围和分号.
例如,考虑一下:
if(httpRequestFailed())
HTTP_REQUEST_RETURN_ERROR(404);
else
processResults();
Run Code Online (Sandbox Code Playgroud)
没有do ... while(0),上面会出现语法错误,因为在if和之间会有多个语句else.只是在宏扩展中添加大括号并不是很干净,因为如上所述的类似于语句的用法会导致扩展
if(httpRequestFailed())
{ ... /* code omitted */ };
Run Code Online (Sandbox Code Playgroud)
这不是很干净,代码范围之后的大括号通常不会后跟分号.