Tuesday, 15 July 2014

c - Purpose of #define foo() do { } while (0) -



c - Purpose of #define foo() do { } while (0) -

while browsing sources of lincan driver, found macros baffled me.

#else /*config_preempt*/ #define can_preempt_disable() { } while (0) #define can_preempt_enable() { } while (0) #endif /*config_preempt*/

i understand usefulness of

do { ...; if(condition) break; ... } while (0);

using break kind of throw. semi-understand wrapping sequence of functions

#define foo() { foo(); bar(); } while (0)

to avoid caveats braceless if. understand "no-op statements" required #define. why particular kind? specifically, empty braces, false condition, do...while? syntax caveats can't quite grasp?

the complete passage relevant file is:

#if !defined(config_preempt_rt) && ( defined(config_preempt) || (linux_version_code >= kernel_version(2,6,0)) ) #define can_preempt_disable preempt_disable #define can_preempt_enable preempt_enable #else /*config_preempt*/ #define can_preempt_disable() { } while (0) #define can_preempt_enable() { } while (0) #endif /*config_preempt*/

thus, first part code when you've asked pre-emption protection, otherwise empty, do-nothing, loops.

i guess they're written usual reasons, i.e. ensure macro still valid statement.

there shouldn't terminating semicolon in definition, since in code using these, such this function begins:

int c_can_wakeup_tx(struct canchip_t *chip, struct msgobj_t *obj) { can_preempt_disable(); ...

so, macro used other function call, , semicolon right there macro invoked. normal.

update 2: defining ; leads double semicolons ugly, @ to the lowest degree in opinion. empty brace pair {} work guess, do/while build more idiomatic since it's used in cases these.

update 3: pointed out in comment, empty brace pair won't work since can't set semicolon after call. aah. thanks!

c loops

No comments:

Post a Comment