how does do{} while(0) work in macro?

前端 未结 3 1375
迷失自我
迷失自我 2020-12-01 19:30

Though this topic has been discussed many times in this forum and all other forums, still I have doubts. Please help.

How does the do{} while(0) in macr

相关标签:
3条回答
  • 2020-12-01 20:16

    @Kragen has answered what the do...while construct is for - it basically makes a macro much safer to use.

    However, I don't think it answers the question of "how does this work?":

    #define preempt_disable()    do { } while (0)
    

    The macro is defined to do nothing. Why would you want to do nothing?

    • In some cases you want to use a macro as a placeholder for doing something. For example, you might write code on one system where "preempt" isn't an issue, but you know the code might be ported to a system where "preempt" needs some special handling. So you use a macro everywhere the second system needs it (so that the handling is easy to enable later), but for the first system you then define that macro as a blank macro.

    • In some cases you may want to do things like a task that is made up of different parts, (e.g. START_TABLE(); TABLE_ENTRY(1); TABLE_ENTRY(2); END_TABLE();). This makes a nice clean clear implementation of your table. But then you find that you don't actually need the END_TABLE() macro. To keep the client code tidy, you leave the macro defined, and simply define it to do nothing. That way, all your tables have an END_TABLE and the code is easier to read.

    • A similar case can occur with two states (enable/disable) where one state needs the macro to do something, but the other state just happens by default, so the implementation of one is "empty" - you still use the macro because it makes the client code easier to understand, because it explicitly states the places where things are enabled or disabled.

    0 讨论(0)
  • 2020-12-01 20:20

    See this link for a better explanation than I could give.

    0 讨论(0)
  • 2020-12-01 20:33

    IIRC the use of the do-while in macros is to make them look more like a normal function invocation; there are some subtle syntax issues around unbraced if statements and things like that. Without the do-while the macro might look like a normal function invocation but would work differently.

    I would guess that in this case those macros are being used so certain function calls compile away to nothing; it looks like that might be what you get if CONFIG_PREEMPT wasn't set, so certain parts of the kernel that are only necessary for preempt simply vanish without it. So those loops do not disable preempt or reschedule anything; there'll be another definition (probably a real function) elsewhere in the kernel source.

    0 讨论(0)
提交回复
热议问题