Does pointer arithmetic still work outside the array?

前端 未结 3 1827
孤街浪徒
孤街浪徒 2021-01-04 19:43

I am always reading that pointer arithmetic is defined as long as you don\'t leave the bounds of the array. I am not sure I completely understand what this means and I was a

3条回答
  •  花落未央
    2021-01-04 20:20

    What you're doing works on the implementation you're using, as well as most popular implementations, but it's not conforming C. As chris cited,

    §6.5.6/8: If both the pointer operand and the result point to elements of the same array object, or one past the last element of the array object, the evaluation shall not produce an overflow; otherwise, the behavior is undefined

    The fact that it's undefined will probably become increasingly important in the future, with more advanced static analysis allowing compilers to turn this kind of code into fatal errors without incurring runtime cost.

    By the way, the historical reason for subtracting pointers not within the same array being undefined is segmented memory (think 16-bit x86; those familiar with it will want to think of the "large" memory model). While pointers might involve a segment and offset component, a compiler could do the arithmetic just on the offset component to avoid runtime cost. This makes arithmetic between pointers not in the same segment invalid since the "high part" of the difference is lost.

提交回复
热议问题