What are convincing examples where pointer arithmetic is preferable to array subscripting?

前端 未结 9 645
没有蜡笔的小新
没有蜡笔的小新 2020-12-30 09:23

I\'m preparing some slides for an introductory C class, and I\'m trying to present good examples (and motivation) for using pointer arithmetic over array subscripting.

9条回答
  •  太阳男子
    2020-12-30 10:06

    Pointer arithmetic may look fancy and "hackerish", but I have never encountered a case it was FASTER than the standard indexing. Just the opposite, I often encountered cases when it slowed the code down by a large factor.

    For example, typical sequential looping through an array with a pointer may be less efficient than looping with a classic index on a modern processors, that support SSE extensions. Pointer arithmetic in a loop sufficiently blocks compilers from performing loop vectorization, which can yield typical 2x-4x performance boost. Additionally, using pointers instead of simple integer variables may result in needless memory store operations due to pointer aliasing.

    So, generally pointer arithmetic instead of standard indexed access should NEVER be recommended.

提交回复
热议问题