Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can we replace `if (!x) x=true` with `x=true` directly?

I am doing some refactoring work and came across such a piece of code:

bool x = false;

...// maybe some logical work would change the value of x.

if (!x) {
  x = true;
}

So, I am curious whether I can do such a replacement:

x = true;

As you can see, I assign x to true directly, which may reduce the number of instructions in the CPU, but I am not sure if there are any hidden dangers.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Any suggestions?

>Solution :

x = true; is clearer than if (!x) { x = true; }.

From performance point of view, former avoids branching, whereas the later doesn’t touch to "cacheline" (in one case).

And compiler might change one to another with as-is rule anyway.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading