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

跟風遠走 提交于 2019-11-27 09:07:47

@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.

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

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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!