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

前端 未结 3 1394
迷失自我
迷失自我 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.

提交回复
热议问题