Is it better to check a variable before setting its value in C ++?

If I have a boolean and some code that can change it, and then I want to set it to true , should I check if it is false ?

For instance:

 bool b = false; // Some code // Here "b" can be true or false if (cond) { b = true; } 

against

 bool b = false; // Some code // Here `b` can be `true` or `false` if (cond && !b){ b = true; } 

Which is faster?

Note

I ask that due to the following implementation of Sieve of Eratosthenes : http://bloc.gerardfarras.com/wp-content/uploads/2011/12/erastotenes.txt

 if (( i % divisor == 0 ) && ( numsprimers[i] == 0 )) { numsprimers[i] = 1; } 

(If numsprimers[i]==1 this means that i not a prime, and if it is 0, then it can be prime or not)

+6
source share
2 answers

This is very very strange, but generally speaking, it’s better to just change the value.

In any case, checking and setting the value has approximately the same overhead, so why do you need to do both in some cases?

Now, if you are interested in whether to overwrite some kind of user-defined type (say, a list of 100,000 words) or if you need to check whether you need to overwrite it first (say, just by checking a boolean value or timestamp), then you should first check because the cost of checking a boolean or timestamp is much less than storing a large number of words in memory.

This, of course, depends on various things, such as, regardless of whether the memory is stored in your memory, how expensive the β€œcheck” is, how often you need to rewrite the value compared to how often it does not need to be overwritten, and, Of course, the size of the memory.

+2
source

What about:

 if ( b = !!cond ) { } 

Where you check the condition and apply the value to b if b necessary to have a value. If you want b stay true, I say use one of your other examples. This should not change.

0
source

Source: https://habr.com/ru/post/927702/


All Articles