I have read an article with following example:
void func()
{
if (condition1)
a = a + 1;
if (condition2)
a = a - 1;
}
It says the CC is 3 as there are three possible paths. How come? Why not 4? I Would expect TRUE,TRUE; FALSE,FALSE; TRUE, FALSE and FALSE, TRUE.
Does not matter what the statements are. CC=Ifs-EndPoints+2. It is always 3 for 2 IFs and one ending..
If your article “says the CC is 3 as there are three possible paths” then the article is missing some of the detail. The wikipedia definition of cyclomatic complexity defines it in terms of the number of nodes and edges in the graph of the function: M = E − N + 2P.
This is the graph of your function:
(+)
|
(if)
|
| (stmt)
|/
(if)
|
| (stmt)
|/
(*)
E = 7, N = 6, P = 1 so M = 7 – 6 + 2*1 = 3.
7
TRUE,TRUE has the same outcome as FALSE,FALSE.
//TRUE,TRUE
void func()
{
a = 1;
if (condition1)
a = a + 1; // a == 2
if (condition2)
a = a - 1; // a == 1
// a == 1
}
//FALSE,FALSE
void func()
{
a = 1;
if (condition1)
a = a + 1; // a == 1
if (condition2)
a = a - 1; // a == 1
// a == 1
}
//TRUE, FALSE
void func()
{
a = 1;
if (condition1)
a = a + 1; // a == 2
if (condition2)
a = a - 1; // a == 2
// a == 2
}
//FALSE, TRUE
void func()
{
a = 1;
if (condition1)
a = a + 1; // a == 1
if (condition2)
a = a - 1; // a == 0
// a = 0
}
5