Most elegant way to write a one-shot 'if'

前端 未结 9 2197
情话喂你
情话喂你 2020-12-22 21:51

Since C++ 17 one can write an if block that will get executed exactly once like this:

#include 

        
9条回答
  •  我在风中等你
    2020-12-22 22:17

    C++ does have a builtin control flow primitive that consists of "(before-block; condition; after-block)" already:

    for (static bool b = true; b; b = false)
    

    Or hackier, but shorter:

    for (static bool b; !b; b = !b)
    

    However, I think any of the techniques presented here should be used with care, as they are not (yet?) very common.

提交回复
热议问题