What is the reason to define macro this way:

#define test_errno(msg) do{if (errno) {perror(msg); exit(EXIT_FAILURE);}} while(0)

I mean what is the reason behind do{}while(0)? Of course it will be done once only, zero is constant, cannot change to nonzero somehow, so why to use such construction?

有帮助吗?

解决方案

It allows things like

if (condition) 
   test_errno(...);

to work properly with or without braces.

其他提示

There is no good reason in this case. In similar constructs, it is useful for the statements inside to have continue and break to do useful things.

#define test_errno(msg) do {if (cond1) break;   \
                            if (cond2) break;   \
                            if (cond3) break;   \
               do_something_if_all_condtions_met();} while(0)
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top