Pregunta

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?

¿Fue útil?

Solución

It allows things like

if (condition) 
   test_errno(...);

to work properly with or without braces.

Otros consejos

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)
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top