Hacker News new | ask | show | jobs
by filereaper 2708 days ago
Enjoyed this article, anybody know the significance of adding the do..while(0) loop within the macro starting Linux 1.3?

Was curious if it guards against some C pre-processor issues.

  /** include/asm-i386/system.h */
  #define switch_to(tsk) do {
    [...]
  } while (0)
2 comments

Just to add more context, this is a very common cpp (c pre-processor) idiom. You'll find it in most non-trivial C projects somewhere.
Abbreviating the C Preprocessor as cpp is very confusing imho.
It's a common abbreviation older than C++. You used to even be able to run the c pre processor on arbitrary non-C files by using the cpp command.
You still can.
Tell that to CPPFLAGS.
It enables you to invoke the macro as if it were an expression statement consisting of a function call, regardless of where it appears.

For details, see http://c-faq.com/cpp/multistmt.html:

In particular, a single statement. I'm sure the link covers it, but:

    if (foo)
      MULTI_LINE_MACRO;
Breaks without some wrapper like if (1) { A; B; } or do { A; B; } while (0):

    if (foo)
      A;
      B;  // oops, unconditional (e.g., "goto fail")
It also gives you a nice scope to keep local variables in, but there are other ways to accomplish that too.
Yeah, that's a good point too.