Home > Software engineering >  Can we replace `if (!x) x=true` with `x=true` directly?
Can we replace `if (!x) x=true` with `x=true` directly?

Time:11-24

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.

Any suggestions?

CodePudding user response:

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.

CodePudding user response:

It depends on your exact context of course, but if the purpose here after that block is to have x be equal to true, then x = true; is the same (and much more readable).

CodePudding user response:

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

If the type of x is bool such as in the example, then yes. For other types there may be a difference.

  •  Tags:  
  • c
  • Related