You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

这段C++代码的圈复杂度是多少?是否存在仅执行default分支的路径?

int x = 99;
int a = 4;
int parity;
while (x < 100)
{
    if (a % 2 == 0)
    {
        parity = 0;
    }
    else
    {
        parity = 1;
    }
    switch (parity)
    {
    case 0:
        cout << "even ";
    case 1:
        cout << " odd ";
    default:
        cout << "Error";
    }
    x++;
}
int p = 1;

是否存在仅执行default分支的独立路径?

不存在。因为parity被if-else语句严格限制为0或1,进入switch后必然会先匹配case 0或case 1分支,再通过贯穿特性走到default分支,没有任何路径能跳过前两个case直接只执行default。

代码的圈复杂度是多少?

圈复杂度确实是4。计算逻辑如下:
从实际可达的控制流来看,代码里有三个核心判定点:

  1. while循环的条件判断(进入循环/直接跳过)
  2. if-else的条件判断(给parity赋值0/1)
  3. switch语句的两种有效分支(对应parity=0和parity=1的执行路径)
    按照圈复杂度“判定点数量+1”的计算规则,3个判定点加1得到结果4;用控制流图的边数-节点数+2的公式计算,结果也为4。

内容的提问来源于stack exchange,提问作者Ramneet Singh

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 08:10:28