Re: shame on MISRA



Richard Pennington wrote:
Stefan Reuther wrote:
disident@xxxxxxxxxxxx wrote:
Yes, this is correct. You should not modify, alias or copy the pointers.
Work with arrays and indexes only.
a = &x[i] is absolutely equivalent to a=x+i (assuming i is an integer
and a&x are pointers of the same type).

No, it's not. While '&x[i]' requires the element i to exist (i.e. array
x must have at least i+1 elements), 'x+i' doesn't. If your compiler can
do array bounds checks, it will probably do that for '&x[i]', but not
for 'x+i'.


Stefan


Hmm. &x[i] does not require that x has i+1 elements. In fact it is explicitly mentioned in the standard when x has exactly i elements.

I don't think the standard has changed the fact that for a pointer (or array name) x and an integer i that

x + i == i + x == &x[i] == &i[x]

Has it?


The C standard says that "x + i" and "&x[i]" have the same value. However, &x[i] is only valid if x has at least i elements (not necessarily (i + 1) - the address beyond the top of the array is also valid). The compiler should generate the expected code for &x[i] with out of range i, but it is not guaranteed.

However, any good C compiler, or other C analyser like lint, will interpret "&x[i]" and "x + i" differently, as they operate on a higher level than blind code generation. On an array access, they can do a certain amount of static range checking - some C compilers may even have the option for run-time range checking. The compiler may also be able to do better alias analysis and therefore generate better code with the array access (since it knows the range the resultant pointer could take).

All this is, of course, subservient to the golden rule of writing understandable code. If "i" is an index into the array "x", then the correct form is "&x[i]" - "x + i" does not say what you mean, and is therefore bad code.


-Rich
.