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,753
  • 72
  • 57
  • 129
4pie0
  • 29,204
  • 9
  • 82
  • 118

2 Answers2

3

It allows things like

if (condition) 
   test_errno(...);

to work properly with or without braces.

DrC
  • 7,528
  • 1
  • 22
  • 37
  • 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
  • 56,922
  • 16
  • 83
  • 148