431

I've been seeing that expression for over 10 years now. I've been trying to think what it's good for. Since I see it mostly in #defines, I assume it's good for inner scope variable declaration and for using breaks (instead of gotos.)

Is it good for anything else? Do you use it?

6
  • Have a look at this question. Nov 2, 2008 at 21:38
  • 13
    Actually, it is not a duplicate since the linked q/a is not specific to define. It's easy to compare both answers to state it's not a duplicate.
    – Doomsday
    May 18, 2012 at 15:44
  • See "decrement_used_memory" of Redis line 53 [link]github.com/antirez/redis-tools/blob/master/zmalloc.c
    – yet
    Dec 9, 2012 at 21:57
  • The duplicate is with the question marked as possible duplicate (first line of the post), not with the question given by Federico A. Ramponi.
    – Étienne
    May 2, 2013 at 8:52
  • 2
    other variants of this do { ... } while ((void)0, 0) used to silence compiler warnings about "constant condition".
    – Amro
    Jan 1, 2016 at 0:56

5 Answers 5

616

It's the only construct in C that you can use to #define a multistatement operation, put a semicolon after, and still use within an if statement. An example might help:

#define FOO(x) foo(x); bar(x)

if (condition)
    FOO(x);
else // syntax error here
    ...;

Even using braces doesn't help:

#define FOO(x) { foo(x); bar(x); }

Using this in an if statement would require that you omit the semicolon, which is counterintuitive:

if (condition)
    FOO(x)
else
    ...

If you define FOO like this:

#define FOO(x) do { foo(x); bar(x); } while (0)

then the following is syntactically correct:

if (condition)
    FOO(x);
else
    ....
21
  • 8
    Wouldn't #define FOO(x) if(true){ foo(x); bar(x); } else void(0) also work even though it's much uglier?
    – Adisak
    Aug 7, 2013 at 22:39
  • 6
    @user10607: Yes, that works if your macro expansions is a list of expressions. However, if you want to include an if or while inside the expansion, that trick won't work either. Nov 3, 2014 at 19:45
  • 25
    I still think this is UGLY, and SLOPPY coding, and CAN be avoided, if coded correctly. this goes back to some of the common sense C rules, of ALWAYS using curly's on your IF statements, even if you only have ONE operation after the IF. This should be standard practice, IMVHO...
    – LarryF
    Jul 16, 2015 at 20:37
  • 76
    @LarryF: The problem is, if you're writing a header file for use by others, you don't get to choose how other people are going to use your macro. In order to avoid unexpected surprises inflicted upon your users, you have to use a technique like the above to make your macro behave as any other C statement would behave. Jul 16, 2015 at 23:39
  • 6
    @AaronFranke because {...}; is actually made of two statements, the {...} part and another empty statement after it. do {...} while(0); is one statement, though. Larry/Marco when users write FOO(a, b, c) they expect it (unless explicitly intended otherwise) to result in an expression, much like a call to a void-returning function. Yours is actually the sloppy approach. The code style convention of your user should be none of your concern.
    – yonil
    Jun 26, 2020 at 10:06
138

It is a way to simplify error checking and avoid deep nested if's. For example:

do {
  // do something
  if (error) {
    break;
  }
  // do something else
  if (error) {
    break;
  }
  // etc..
} while (0);
8
  • 19
    er, factor it into a method, and use early return. Nov 2, 2008 at 23:35
  • 17
    or... just use do { } while(0).
    – nickf
    Nov 2, 2008 at 23:48
  • 86
    Or use goto. No, seriously, if (error) goto error; and a error: ... near the end seems like a cleaner version that accomplishes the same thing, to me.
    – FireFly
    Apr 23, 2014 at 17:46
  • 6
    @WChargin: the "goto fail" code in the article you linked too would have failed with a "break" too. Somebody just duplicated a line there. It wasn't goto's fault.
    – Niccolo M.
    Jun 15, 2014 at 11:15
  • 6
    @NiccoloM. "granted, goto wasn't the error, which actually makes it even funnier"
    – wchargin
    Jun 15, 2014 at 17:36
113

It helps to group multiple statements into a single one so that a function-like macro can actually be used as a function. Suppose you have:

#define FOO(n)   foo(n);bar(n)

and you do:

void foobar(int n) {
  if (n)
     FOO(n);
}

then this expands to:

void foobar(int n) {
  if (n)
     foo(n);bar(n);
}

Notice that the second call bar(n) is not part of the if statement anymore.

Wrap both into do { } while(0), and you can also use the macro in an if statement.

4
  • 4
    Very clear answer. +1 Jun 23, 2015 at 18:57
  • 2
    Clearly understood. ;)
    – Whoami
    Jul 6, 2016 at 6:04
  • Why not just put braces around it? #define FOO(n) {foo(n);bar(n)}
    – endolith
    Aug 27, 2021 at 19:21
  • 4
    @endolith Because #define FOO(n) {foo(n);bar(n)} would expand to {foo(n);bar(n)}. Notice that there is no semicolon after bar(n).
    – John
    Oct 19, 2021 at 12:37
23

It is interesting to note the following situation where the do {} while (0) loop won't work for you:

If you want a function-like macro that returns a value, then you will need a statement expression: ({stmt; stmt;}) instead of do {} while(0):


#include <stdio.h>

#define log_to_string1(str, fmt, arg...) \
    do { \
        sprintf(str, "%s: " fmt, "myprog", ##arg); \
    } while (0)

#define log_to_string2(str, fmt, arg...) \
    ({ \
        sprintf(str, "%s: " fmt, "myprog", ##arg); \
    })

int main() {
        char buf[1000];
        int n = 0;

        log_to_string1(buf, "%s\n", "No assignment, OK");

        n += log_to_string1(buf + n, "%s\n", "NOT OK: gcc: error: expected expression before 'do'");

        n += log_to_string2(buf + n, "%s\n", "This fixes it");
        n += log_to_string2(buf + n, "%s\n", "Assignment worked!");
        printf("%s", buf);
        return 0;
}
2
  • 8
    This is a GCC extension. In C++11 you could do the same thing with a lambda, though. Jul 8, 2015 at 6:32
  • TIL statement expressions. Neat. How does it look with a lambda? I'm curious. A lambda returns a functor, essentially, you still have to call it, then return the result from the macro. both the lambda and the call need to form a single statement. How do you do it? operator,?
    – yonil
    Jun 26, 2020 at 10:17
-7

Generically, do/while is good for any sort of loop construct where one must execute the loop at least once. It is possible to emulate this sort of looping through either a straight while or even a for loop, but often the result is a little less elegant. I'll admit that specific applications of this pattern are fairly rare, but they do exist. One which springs to mind is a menu-based console application:

do {
    char c = read_input();

    process_input(c);
} while (c != 'Q');
3
  • 1
    It's available in C#, too, which doesn't have macros. I'm not sure why someone down-voted this reply but I see it as the almost-right answer, except it overlooked the explicit "0" in the while condition. Please, people, if you down-vote someone's reply please comment.
    – Jon Davis
    Nov 2, 2008 at 22:36
  • 23
    I wasn't the one to downvote; however, the question is very specific, and the answer is true in general but out of context.
    – tzot
    Nov 2, 2008 at 23:04
  • 2
    Statement is correct but it is out of context. Mar 18, 2019 at 10:08

Not the answer you're looking for? Browse other questions tagged or ask your own question.