Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding `bool` to `float`

I'm maintaining some code and came across this snippet:

int num = 0;
float sum = 0.0;
bool value[rows][cols]; //initialized elsewhere in the code
for(int i = 0; i < rows; i++)
    for(int j = 0; j < cols; j++)
        if(value[i][j] == true) {
            sum += value[i][j]; //shouldn't this be equivalent to "sum += 1;"
                                //as it is in the if block?
            num++;
        }
float ans = 1.0;
if(num > 12)
    ans = sum / num;

Is the guy who wrote this code originally doing something fiendishly clever here, or should ans always be 1? As far as I can tell, num and sum should always be exactly the same value, no?

like image 519
wolfPack88 Avatar asked Mar 17 '26 15:03

wolfPack88


2 Answers

This will the same as sum += 1 since a true value will be converted to 1 this is covered in the draft C++ standard section 4.9 Floating-integral conversions which says:

If the source type is bool, the value false is converted to zero and the value true is converted to one.

The additive operators will cause the usual arithmetic conversions to be performed on their operands. Which in this case will be covered by this case:

Otherwise, if either operand is float, the other shall be converted to float.

and we know that E1 += E2 is equivalent to E1 = E1 + E2 from section 5.17 Assignment and compound assignment operators which says:

The behavior of an expression of the form E1 op = E2 is equivalent to E1 = E1 op E2 except that E1 is evaluated only once.[...]

like image 157
Shafik Yaghmour Avatar answered Mar 19 '26 05:03

Shafik Yaghmour


The answer is not fiendlishly clever because the if statement is still present.

To be clever, one would do something like this:

for(int i = 0; i < rows; i++)
{
    for(int j = 0; j < cols; j++)
    {
       sum += value[i][j];  // Add 1 if true, 0 if false.
       num += value[i][j];  // Add 1 (increment) if true, add 0 if false
    }
}

The assumption is that a bool type will convert to 1 if true, and 0 if false. This is how things were done in the dawn of computers.

If the true evaluates to some nonzero value other than 1, this code will not work correctly.

Upon further analysis, the sum and num will have the same value at the end of the loops. So, only use num and convert to float at the end of the loop.

like image 42
Thomas Matthews Avatar answered Mar 19 '26 05:03

Thomas Matthews



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!