C++

Asked • 07/27/19

Why use apparently meaningless do-while and if-else statements in macros?

In many C/C++ macros I'm seeing the code of the macro wrapped in what seems like a meaningless `do while` loop. Here are examples. #define FOO(X) do { f(X); g(X); } while (0) #define FOO(X) if (1) { f(X); g(X); } else I can't see what the `do while` is doing. Why not just write this without it? #define FOO(X) f(X); g(X)

1 Expert Answer

By:

Kyle A. answered • 05/05/20

Tutor
New to Wyzant

Senior Software Engineer Specializing in Systems Programming

Still looking for help? Get the right answer, fast.

Ask a question for free

Get a free answer to a quick problem.
Most questions answered within 4 hours.

OR

Find an Online Tutor Now

Choose an expert and meet online. No packages or subscriptions, pay only for the time you need.