【问题标题】:C static array initialization and cyclomatic complexityC静态数组初始化和圈复杂度
【发布时间】:2014-07-28 20:54:11
【问题描述】:

我有以下代码:

typedef struct A_{

  void* values;
}A;

typedef struct C_{

  int array_C[3][3];
}C;

typedef struct B_{

  C c;
}B;

int main(void)
{
    B* b;

    A array_A[2] = {
                        {
                            &(b->c.array_C)   \\ line 23
                        },

                        {
                            &(b->c.array_C)    \\ line 27
                        }
                  };

   return 0;
}

我的错误在第 23 和 27 行,它说 &(b->c.array_C) 应该是 const。 我做错了什么? 数组的地址不是常量吗?

我这样做的原因是因为我需要提高函数的圈复杂度 使用 340 个 if 语句,当每个 if 语句的格式如下:

if( exspretion )
{
   foo( address_of_array);
   return false;
}

如果我将 340 个 if 语句更改为一个 while 循环,该循环运行 340 次并从上述数组中获取 foo 函数的参数,那么圈复杂度会更好吗?

【问题讨论】:

  • 问题是表达式&(b->c.array_C) 要求在编译时知道b 的值,但事实并非如此。
  • b 是未初始化的指针。你应该先用一个有效的地址初始化它。
  • 这种变化真的会提高代码的清晰度,还是会愚弄工具,让其认为通过将真实代码隐藏在数组中来更简单?
  • @DrewMcGowen 为什么表达式要求在编译时知道b 的值?
  • @ThoAppelsin 只是摆脱了 OP 提到的“应该是 const”警告

标签: c arrays initialization cyclomatic-complexity


【解决方案1】:

要解决您看到的错误,行:

B* b;  

可以改成:

B b, *pB;//create an instance of B, and a pointer to B at the same time. 
pB = &b; //now, pB is initialized to point at a real place in memory. (i.e. b)  
         //(use it instead of b in your code)  

Main 现在看起来像这样:

int main(void)
{
    B b, *pB;
    pB = &b;

    A array_A[2] = {
                        {
                            &(pB->c.array_C)   // line 23
                        },

                        {
                            &(pB->c.array_C)    // line 27
                        }
                  };
   //assignments can now be made to the actual array elements  
   pB->c.array_C[0][0]=3;//for example

   //Question:  How are you planning on using   array_A[0], array_A[1]?  (A is a void *)

   return 0;
}  

关于圈复杂度
还有您的问题:
...如果我将 340 个 if 语句更改为一个 while 循环...圈复杂度会更好?

一段源代码的

圈复杂度是通过源代码的线性独立路径的数量的计数。例如,如果源代码不包含诸如 IF 语句或 FOR 循环之类的决策点,则复杂度将为 1,因为通过代码只有一条路径。 (来自HERE

圈复杂度而言,for 循环不会比 340 次顺序调用有所改进,但就可维护性和可读性而言,这将是一个很大的改进。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-11
    • 1970-01-01
    相关资源
    最近更新 更多