# What's the point of having this code?

I am researching OpenCV code and I came across the following few lines:

Var function:

``````CvMat* _err;
int i, count = _err->rows*_err->cols, goodCount = 0;
for( i = 0; i < count; i++ )
goodCount += mask[i] = err[i] <= threshold;    // This line is strange for me
return goodCount;
```

```

What does the line I have specified actually do? Because, call me strange, I've never seen anything like it.

For information:

• Yes, the code works: D
• The code is part of the function `CvModelEstimator2::findInliers`

.
+3

source to share

This line is evil .

However, it assigns `1`

`mask[i]`

if `err[i] <= threshold`

and `0`

otherwise.

Then it increments `goodCount`

if the condition is met.

``````mask[i] = (err[i] <= threshold);
```

```
+8

source

``````goodCount += mask[i] = err[i] <= threshold;
```

```

You can use the C operator precedence table to determine the order of operations here, but it's pretty unambiguous anyway:

• Compare err [i] with the threshold. This results in bool (true or false).
• Assign the result to the mask [i]. I think bool will be converted to number here, which will be 1 for true or 0 for false.
• Use the new mask value [i] (which is the result of the operator `=`

) to increase goodCount (basically, goodCount will contain the number of "true" values โโfound in step 1).

For me, the most subtle part of this line is that the assignment returns a reference to the left side (i.e. target). This sometimes occurs in less complex terms:

``````if ((mem = malloc(42)) == NULL)
throw ...
```

```
+4

source

``````goodCount += mask[i] = err[i] <= threshold;
```

```

Mix assignment and comparison in the same statement are usually bad ideas.

The recommended approach is to (1) know what the precedence of the operators involved is, and (2) split the statement into multiple statements to improve readability.

0

source

All Articles