我正面临一个宏的问题,我无法弄清楚为什么.
这是宏:
#define WAIT(condition, max_time) \
do { \
int int_loop_wait=0; \
while(1) \
{ \
if(condition) { break; } \
sleep(1); \
if(int_loop_wait>=max_time) { break; } \
int_loop_wait++; \
} \
} while(0) \
Run Code Online (Sandbox Code Playgroud)
我收到了错误
"如果(条件){break;}"预期声明"行"
有谁理解这个错误?
sha*_*oth 30
问题是反斜杠后跟一个空格一起被识别为一个转义序列,它实际上取消了反斜杠.Visual C++ 10甚至会error C2017: illegal escape sequence在那里发布.
代码段中的某些行(例如带有的行while(1))在反斜杠后包含一个或多个空格.一旦反斜杠被视为转义序列并被编译器删除,宏定义就会在该行被截断,而剩余的代码被编译为好像它不属于宏定义.
#define WAIT(condition, max_time) \
do { \
int int_loop_wait=0; \
while(1) \ <<<<<WHITESPACES
{ \<<<this line doesn't belong to macro
if(condition) { break; } \<<<and neither does this
sleep(1); \
if(int_loop_wait>=max_time) { break; } \
int_loop_wait++; \
} \
} while(0) \
Run Code Online (Sandbox Code Playgroud)
\从最后一行删除
我的意思是改变这一行
} while(0) \
Run Code Online (Sandbox Code Playgroud)
通过
} while(0)
Run Code Online (Sandbox Code Playgroud)
然后删除所有空格 \
你有一些行之后包含空格\:
while(1) \
{ \
Run Code Online (Sandbox Code Playgroud)
罪魁祸首是白色空间\.删除它们将解决.
如果行结束时宏定义继续\,但不以空格或任何其他字符结束.
#define WAIT(condition, max_time) \
do { \
int int_loop_wait=0; \
while(1){ \
if(condition) { break; } \
sleep(1); \
if(int_loop_wait>=max_time) { break; } \
} \
} while(0)
Run Code Online (Sandbox Code Playgroud)