I'm using gcovr for the first time and have hit a confusing issue with this code:
for (int i = 0; i < 4; i++)
{
bool a = i & 1;
bool b = i & 2;
if (a && b)
printf("a and b\n");
else if (a && !b)
printf("a not b\n");
else
printf("the other two\n");
}
(The code works as you'd expect, so I'm not going to paste the output.)
However, gcovr decides I don't have full branch coverage:
✓✓ 5 for (int i = 0; i < 4; i++)
{
4 bool a = i & 1;
4 bool b = i & 2;
✓✓✓✓ 4 if (a && b)
1 printf("a and b\n");
✓✓✓✗ 3 else if (a && !b)
1 printf("a not b\n");
else
2 printf("the other two\n");
}
Clearly the one of the four permutations is not handled by the else if
, but only because it's been handled by the first if
.
I'm grumpy because the net result is less than 100% branch coverage. Is this just "the way" or have I fatally misunderstood something?
You may want to refactor:
if (a)
{
if (b)
{
std::cout << "a and b\n";
}
else
{
std::cout << "a and not b\n";
}
}
else
{
std::cout << "not a\n";
}
In your posted code, the a
is evaluated in two if
statements.
The above example removes the else if
condition.