查看Qt Test Framework的一些宏,如QCOMPARE
,这是代码:
#define QCOMPARE(actual, expected) \
do {\
if (!QTest::qCompare(actual, expected, #actual, #expected, __FILE__, __LINE__))\
return;\
} while (0)
如您所见,有一个while循环。我在CryEngine单元测试框架中也发现了同样的事情。我的问题很简单:是否有任何理由使用该循环,或者可能是旧的实现留下的东西?
答案 0 :(得分:6)
您会注意到while
条件始终为false,因此没有实际循环。在预处理器宏中使用块并且最后仍然需要分号是一种常见的技巧(因此使用宏感觉就像使用函数一样,并且不要混淆一些压头)。也就是说,
QCOMPARE(foo, bar); // <-- works
QCOMPARE(foo, bar) // <-- will not work.
这在if
和else
的上下文中非常有用,其中
if(something)
QCOMPARE(foo, bar);
else
do_something();
将扩展为
if(something)
do stuff() while(0);
else
do_something();
有效,而带有块且没有循环结构的多行宏将扩展为
if(something)
{ stuff() }; // <-- if statement ends here
else // <-- and this is at best a syntax error.
do_something();
没有。