Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Advantages of do { } while(0) versus ({ }) in a macro?

Tags:

c

macros

There are plenty of questions on Stack Overflow regarding the use of do { ... } while(0) in macros, but this is a bit different. I understand why do { ... } while(0) is used to wrap multiple lines of code in a macro expansion. But there is another form I often see: ({ ... }).

The ({ }) form has the advantage that it is an expression and can have a "return value". It also (subjectively) reads better than do { } while(0). So why isn't it always used? What advantage is there to using do { } while(0) in a macro instead?

like image 776
Alex D Avatar asked May 27 '15 18:05

Alex D


People also ask

Why do we use do while 0?

You may see a do loop with the conditional expression set to a constant value of zero (0). This creates a loop that will execute exactly one time. This is a coding idiom that allows a multi-line macro to be used anywhere that a single statement can be used.

Do while in macro definition?

A Do… While loop is used when we want to repeat a set of statements as long as the condition is true. The condition may be checked at the beginning of the loop or at the end of the loop.

Why do macros use do while?

In conclusion, macros in Linux and other codebases wrap their logic in do/while(0) because it ensures the macro always behaves the same, regardless of how semicolons and curly-brackets are used in the invoking code.

What does do while 0 mean in C?

The while(0) loop means that the condition available to us will always be false. Function. Not just while(1), but every non-zero integer is capable of giving a similar effect like how the while(1) does.


1 Answers

Because ({...}) is a GCC extension.

like image 135
Quentin Avatar answered Oct 18 '22 04:10

Quentin