Question

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?

Était-ce utile?

La solution

It allows things like

if (condition) 
   test_errno(...);

to work properly with or without braces.

Autres conseils

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)
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top