如何解决此MISRA c ++兼容警告

suh*_*hel 5 c++

int foo(const uint8_t array[]) {
int x;
  for(i=0;i<5;i++){
  x= array[i];
}
return 0;
}
Run Code Online (Sandbox Code Playgroud)

它给出了如下警告,

"参数数组可以声明为const"==>我已经声明了数组const,我用C++编程.

jro*_*rok 7

首先要注意的是它int foo(const uint8_t array[])等效于int foo(const uint8_t* array),即函数采用指向a的指针const uint8_t,而不是数组.指针本身不是const,指针是.签名应该是:

int foo(const uint8_t* const array)  
Run Code Online (Sandbox Code Playgroud)

为了记录,我没有发现这个警告特别有用.该参数由值获取,调用者不关心函数对它的作用.此外,在比较函数签名时,将忽略参数的顶级const限定符,这可能会导致一些混淆.

void foo(int)并且void foo(const int),例如,是相同的签名.

编辑:

因此,根据您的评论,MISRA不知道您不能按值传递数组并抱怨数组索引的工作方式与指针算法不同.Shudder ......问题是你不能const使用数组语法添加顶级,这使得对这两个警告的修复是mutualy独占的.

尝试欺骗它,然后:

typedef const uint8_t Array[];
int foo(const Array arr);
Run Code Online (Sandbox Code Playgroud)

  • 确切地说...我在尝试之前尝试了同样的问题,但后来又开始给出一个不同的警告,例如"规则5-0-15,指针运算除了数组索引使用"==>换行x =数组[i ]. (2认同)