C++: Set bool value only if not set

后端 未结 6 2179
小鲜肉
小鲜肉 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-17 22:53

    You are most likely over-thinking the problem as others already mentioned, so let me do the same. The following might be faster if you can afford to double the statements unrelated to myFlag. In fact, you can get rid of myFlag. OK, here we go:

    while (/*some finite condition*/) {
        if (...) {
            // statements
        } else {
            while (/*some finite condition*/) {
                if (...) {
                   // statements, repeated
                }
            }
            // Do something (as if myFlag was true in the OPs example)
            break;
        }
    }
    

    As with all performance optimization: Measure, measure, measure!

提交回复
热议问题