wolfPack88
wolfPack88

Reputation: 4203

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?

Upvotes: 2

Views: 1289

Answers (3)

Shafik Yaghmour
Shafik Yaghmour

Reputation: 158469

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.[...]

Upvotes: 5

Thomas Matthews
Thomas Matthews

Reputation: 57698

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.

Upvotes: 3

If value is a (two-dimensional) array of bool, then this is equivalent with sum += 1. In contrast with what some people think, a comparison with == true is not the same as an implicit conversion to bool (e. g. in the context of an if statement's condition). Any integer not equal to 1 will be considered different from true.

Upvotes: 1

Related Questions