3

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?

Brian Tompsett - 汤莱恩
  • 5,438
  • 68
  • 55
  • 126
4pie0
  • 28,488
  • 8
  • 76
  • 116

2 Answers2

3

It allows things like

if (condition) 
   test_errno(...);

to work properly with or without braces.

DrC
  • 7,460
  • 1
  • 20
  • 36
  • 1
    a missing `;`. the macro considers this and it needs an ending `;`, so it looks like a real function. – vvy Jun 28 '13 at 01:51
2

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)
wallyk
  • 55,472
  • 16
  • 84
  • 144