Reputation: 159
The following code violates the MISRA C++ rule 5-0-15: Array indexing shall be the only form of pointer arithmetic.
(1)
void doSomething(const uint8_t *&ptr, size_t num) {
ptr += num;
}
Incrementing any pointer also violates the above rule:
(2)
const uint8_t *ptr = ... ;
*ptr++;
I found a very similar question here, but there the questioner uses arrays. I use pointers.
Is there an alternative notation or other method to add numbers to (1)/ increment (2) pointers to get around this violation?
Upvotes: 2
Views: 1271
Reputation: 214780
The "array indexing shall be the only form of pointer arithmetic" rule was inherited from MISRA C:2004 and there were discussions early on about whether the rule made sense or not. The rationale behind the rule was to prevent *(arr+i)
style over arr[i]
style and I don't think anyone is questioning that the latter is more readable and therefore preferred.
However, the examples in the MISRA C:2004 document were confusing - it wouldn't allow array style indexing on variables declared as pointers. But obviously in case of functions, it doesn't matter if we declare something as void func (int* ptr)
or void func (int ptr[])
because these are 100% equivalent thanks to the parameter adjustment rules of C. In fact the []
operator can only be used with pointer operands as explained here: Do pointers support "array style indexing"? So this rule lead to a lot of false positives.
This is one of many things that were fixed in MISRA C:2012, where rule 18.4 is focusing on the pointer artithmetic itself rather than how something was declared. MISRA C:2004 and MISRA C++:2008 will still have the old wording and examples though, so if you are using those, you should take the rule with a grain of salt.
In your specific case, using const uint8_t *&ptr
vs const uint8_t& ptr[]
doesn't matter. ptr += num;
is the questionable part.
Unrelated to the rule, having a pointer to an array of references is pretty fishy as well and would need to be reviewed, in case it is possible to use less complex alternatives.
Upvotes: 2
Reputation: 141698
Array indexing
So use array indexing.
void doSomething(const uint8_t ptr[], size_t num) {
const uint8_t *ptr2 = &ptr[num];
}
Incrementing any pointer
Increment and decrement operators can be used by exception. Doing dereference with incrementing is invalid. There have to be two expressions.
const uint8_t *ptr = somearray;
++ptr;
uint8_t val = *ptr;
Upvotes: 2