C++: Set bool value only if not set

后端 未结 6 2172
小鲜肉
小鲜肉 2020-12-17 22:19

I have code in my C++ application that generally does this:

bool myFlag = false;
while (/*some finite condition unrelated to myFlag*/) {
    if (...) {
               


        
6条回答
  •  执笔经年
    2020-12-17 22:53

    You do realize that the check is moot right? If you blindly set it to true and it was not set, you are setting it. If it was already true, then there is no change and you are not setting it, so you effectively can implement it as:

    myFlag = true;
    

    Regarding the potential optimizations, to be able to test, the value must be in the cache, so most of the cost is already paid. On the other hand, the branch (if the compiler does not optimize the if away, which most will) can have a greater impact in performance.

提交回复
热议问题