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

前端 未结 9 1994
情话喂你
情话喂你 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:14

    In C++17 you can write

    if (static int i; i == 0 && (i = 1)){
    

    in order to avoid playing around with i in the loop body. i starts with 0 (guaranteed by the standard), and the expression after the ; sets i to 1 the first time it is evaluated.

    Note that in C++11 you could achieve the same with a lambda function

    if ([]{static int i; return i == 0 && (i = 1);}()){
    

    which also carries a slight advantage in that i is not leaked into the loop body.

    0 讨论(0)
  • 2020-12-22 22:14

    Based on @Bathsheba's great answer for this - just made it even simpler.

    In C++ 17, you can simply do:

    if (static int i; !i++) {
      cout << "Execute once";
    }
    

    (In previous versions, just declare int i outside the block. Also works in C :) ).

    In simple words: you declare i, which takes default value of zero (0). Zero is falsey, therefore we use exclamation mark (!) operator to negate it. We then take into account the increment property of the <ID>++ operator, which first gets processed (assigned, etc) and then incremented.

    Therefore, in this block, i will be initialized and have the value 0 only once, when block gets executed, and then the value will increase. We simply use the ! operator to negate it.

    0 讨论(0)
  • 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.

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