Programming tip #4 — do { } while (0)

Kosta Zertsekel
Aug 31, 2018 · 2 min read

What’s the problem with below macro written in C language?

#define SWAP(x, y) \
tmp = x; \
x = y; \
y = tmp

In short, it does not always work. To rephrase, it does not work. Why?

if (x > y)
SWAP(x, y);
else
printf("no swap\n");

Well, the macro expands into three lines of code and this is bad for the health of the if statement…

if (x > y)
tmp = x;
x = y;
y = tmp;
else
printf("no swap\n");

Clearly, this is a bad code and will just fail compilation.

There are also other cases to ruin your day using C macro not properly.

So, to solve the above and other widespread problems let’s write a macro in a different way:

do { ... } while (0)

For example:

#define SWAP(x, y)   \
do { \
tmp = (x); \
(x) = (y); \
(y) = tmp; } \
while (0)

So, our source code after C preprocessor become quite good looking:

if (x > y)
do { tmp = ... } while (0);
else
printf("no swap\n");

The above code is always OK. Also, do { } while (0) gives us other important perks as described here.

This technique is widely used throughout the Linux kernel.

So, let’s use it in our code.

— Kosta Z

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade