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?
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.
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.
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.
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.
Because ({...})
is a GCC extension.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With