I am familiar with the inaccuracies of adding/subtracting floats together, but I'm wondering if adding any float to a float value of zero would result in similar inaccuracies as I'm not completely familiar with how floats are added together in such a scenario.
To put my question simply:
float sum = 0.0f;
sum += value;
assert(sum == value); // Is this guaranteed?
(EDIT: As pointed out in the comments, a similar question exists where if adding zero to a float will produce a change to the variable. I could understand how a CPU would be optimized to ignore the addition if the operand is zero, however I'm wondering if the opposite is guaranteed to be true where if adding a non-zero float operand to a variable that's storing a zero is possible to result in a value unequal to the non-zero value being added.)
For clarification why this question was stemmed in my mind, the actual code I'm working on involves clearing a float to zero under certain conditions and then incrementing the float by a certain value outside of the conditional block, but I thought it might be better to instead set the float to the value instead and skip incrementing it.
For example:
float sum = 0.0f;
for (auto && thing : things)
{
if (thing.someCondition)
sum = 0.0f;
else if (thing.otherCondition)
{ /* more code here... */ }
else
{ /* more code here... */ }
sum += thing.value;
}
Compared to:
float sum = 0.0f;
for (auto && thing : things)
{
if (thing.someCondition)
{
sum = thing.value;
continue; // Continue to skip incrementing.
}
else if (thing.otherCondition)
{
/* more code here... */
}
else
{
/* more code here... */
}
sum += thing.value;
}
(Ignore the fact that the last block of code could have the increment logic moved into the other cases and avoid using continue
. I just kept it formatted this way to contrast the previous block where incrementing should always performed.)