Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to resolve this MISRA c++ compliant warning

Tags:

c++

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

it gives a warning as below,

"parameter array could be declared const" ==> i already have declared the array const, i am programming in C++.

like image 998
suhel Avatar asked Jan 28 '14 10:01

suhel


People also ask

What is MISRA C compliance?

The MISRA C and MISRA C++ standards are a set of coding guidelines for the C and C++ programing languages that promote safety, security, and reliability in embedded system software.

How many rules are there in MISRA?

MISRA-C:1998 has 127 rules, of which 93 are required and 34 are advisory; the rules are numbered in sequence from 1 to 127.

What is MISRA coding?

MISRA® is a set of C and C++ coding standards, developed by the Motor Industry Software Reliability Association (MISRA). What's more, MISRA a top coding standard for embedded industries, including automotive. And, MISRA ensures that C/C++ code is safe, secure, and reliable.


2 Answers

First thing to note is that int foo(const uint8_t array[]) is equivalent to int foo(const uint8_t* array), i.e. the function takes a pointer to a const uint8_t, not an array. The pointer itself it not const, the pointee is. The signature should be:

int foo(const uint8_t* const array)  

For the record, I don't find this warning particularly useful. The parameter is taken by value and the caller couldn't care less what the function does with it. Furthermore, top level const qualifiers on parameters are ignored when comparing function signatures, and this can lead to some confusion.

void foo(int) and void foo(const int), for example, are identical signatures.

EDIT:

So, according to your comment, MISRA doesn't know that you can't pass arrays by value and complains that array indexing works differently than pointer arithmetic. Shudder... The problem is that you can't add top level const using the array syntax, which makes fixes to these two warnings mutualy exclusive.

Try tricking it like this, then:

typedef const uint8_t Array[];
int foo(const Array arr);
like image 160
jrok Avatar answered Oct 01 '22 00:10

jrok


Remember that, despite the syntax, the function actually takes a pointer, and is equivalent to

int foo(const uint8_t * array)

So array points to an array of constant bytes; but is not itself constant. The warning is pointing out that, since the function doesn't modify the pointer, it could (and, at least according to this rule, should) be constant:

int foo(const uint8_t * const array)
like image 38
Mike Seymour Avatar answered Oct 01 '22 01:10

Mike Seymour