背景
今天无意间在看某开源的代码,看到了下面的一段比较有趣的代码。
它有趣的地方在于使用do{ …}while(0)循环语句,并且使用的在于defind的宏定义函数中。
/**
* Assert that err matches expect
*/
#define uc_assert_err(expect, err) \
do { \
uc_err __err = err; \
if (__err != expect) { \
fail_msg("%s", uc_strerror(__err)); \
} \
} while (0)
/**
* Assert that err is anything but UC_ERR_OK
*
* Note: Better to use uc_assert_err(<specific error>, err),
* as this serves to document which errors a function will return
* in various scenarios.
*/
#define uc_assert_fail(err) \
do { \
uc_err __err = err; \
if (__err == UC_ERR_OK) { \
fail_msg("%s", uc_strerror(__err)); \
} \
} while (0)
循环语句
我们再写代码过程中用到的循环语句一般都是使用for、while、do{}while(1)这些表达式,do{}while(0)这样的语句几乎或者相对使用的比较少
从功能上来说
do{…}while(1):它是一个死循环语句,语句是否结束靠的是do里面做跳出的判断;
do{…}while(0):它也是一个循环语句,不过它只做一次的do的代码执行就结束了。
从用法来说
do{…}while(0):它的使用是在宏定义函数中。通过宏定义来控制作用域,可以通过避免预处理过程中的一些开销和错误。并且能够确保代码执行行为保持一致性。