I have code in my C ++ application that usually does this:
bool myFlag = false; while (/*some finite condition unrelated to myFlag*/) { if (...) { // statements, unrelated to myFlag } else { // set myFlag to true, perhaps only if it was false before? } } if (myFlag) { // Do something... }
The question I have relates to the else expression of my code. Basically, my loop can set the value of myFlag from false to true, based on a certain condition that is not satisfied. The flag will never be set from true to false. I would like to know which wording makes more sense in terms of performance, and perhaps if this problem is not really a problem due to compiler optimization.
myFlag = true;
OR
if (!myFlag) myFlag = true;
Normally, I would choose the former because it requires less writing code. Nevertheless, I began to think that perhaps this is due to unnecessary writing in memory, and therefore the latter will prevent unnecessary writing if myFlag was already true. But, using the latter, it takes more time because there is a conditional statement and, therefore, to compile the code using additional instructions?
Or maybe I thought too much about it ...
UPDATE 1
Just to clarify a bit ... the goal of my last case is not to write to the memory if the variable was already true. Thus, only write to memory if the variable is false.
ecbrodie
source share