Why do I see multi-line macros wrapped in (seemingly) meaningless loops?

Possible duplicate:
how does {} while (0) work in a macro?

Example from this blog post:

#define VTAILQ_INSERT_BEFORE(listelm, elm, field) do { \ (elm)->field.vtqe_prev = (listelm)->field.vtqe_prev; \ VTAILQ_NEXT((elm), field) = (listelm); \ *(listelm)->field.vtqe_prev = (elm); \ (listelm)->field.vtqe_prev = &VTAILQ_NEXT((elm), field); \ } while (0) 

I have met others, but this emphasizes that I mean well enough

+4
source share
1 answer

Shortly speaking:

If you use a macro without a loop in an ifbraced if else expression, you will be screwed.

 if (a) VTAILQ_INSERT_BEFORE(c, d, e); else blah(b); 

In this case, it will be terribly torn.

More detailed answer here:

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

+7
source

Source: https://habr.com/ru/post/1387469/


All Articles