查看Qt Test Framework的一些宏,例如QCOMPARE
,这是代码:
#define QCOMPARE(actual, expected) \
do {\
if (!QTest::qCompare(actual, expected, #actual, #expected, __FILE__, __LINE__))\
return;\
} while (0)
如您所见,有一个while循环。我也在CryEngine单元测试框架中找到了同样的东西。我的问题很简单:是否有任何理由使用该循环,或者旧的实现中还剩下什么?
最佳答案
您会注意到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();
哪个没有。