I have code in my C++ application that generally does this:
bool myFlag = false;
while (/*some finite condition unrelated to myFlag*/) {
if (...) {
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.