I have a question regarding this metric.
For example, if I have the following code, how many path does the function main
have?
void main()
{
int i = 0, j = 0, k = 0;
for (i=0; i<10; i )
{
for (j=0; j<10; j )
{
for (k=0; k<10; k )
{
if (i < 2 )
printf("value is more than 2\n");
if (i > 5)
printf("value is less than 5\n");
}
}
}
}
The first three for loops should have 3 paths and one additional that bypasses all control flow statements, then what about the nested if statement? Is it 1x1 = 1 path?
Anyone without matlab account, the following description is on the website:
A control flow statement introduces branches and adds to the original one path.
if-else if-else: Each if keyword introduces a new branch. The contribution from an if-else if-else block is the number of branches plus one (the original path). If a catch-all else is present, all paths go through the block; otherwise, one path bypasses the block.
For instance, a function with an if(..) {} else if(..) {} else {} statement has three paths. A function with one if() {} only has two paths, one that goes through the if block and one that bypasses the block.
for and while: Each loop statement introduces a new branch. The contribution from a loop is two - a path that goes through the loop and a path that bypasses the loop.
If more than one control flow statement are present in a sequence without any nesting, the number of paths is the product of the contributions from each control flow statement.
For instance, if a function has three for loops and two if-else blocks, one after another, the number of paths is 2 × 2 × 2 × 2 × 2 = 32.
void func()
{
int i = 0, j = 0, k = 0;
for (i=0; i<10; i )
{
for (j=0; j<10; j )
{
for (k=0; k<10; k )
{
if (i < 2 )
;
else
{
if (i > 5)
;
else
;
}
}
}
}
}
In this example, func has six paths: three from the for statements, two from the if statements plus the original path that bypasses all control flow statements.
CodePudding user response:
According to the description:
If more than one control flow statement are present in a sequence without any nesting, the number of paths is the product of the contributions from each control flow statement.
and
The contribution from an if-else block is the number of branches plus one (the original path)
your two if statements contribute 2 paths each, so that's 2 x 2 = 4 paths, and then each of your loop contributes one additional path, so the total would be 7 paths.
However, this description does not make much sense to me, since this code has only one possible path:
if (true) {
// this part is always executed
}
This can seem obvious, but more complicated situations can easily reduce the number of possible paths, just like in your example where there are only three possibilities: either i < 2
or i > 5
or i >= 2 && i <= 5
.
I suppose the metric's description would make sense as an upper bound on the number of paths.