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

前端 未结 9 619
没有蜡笔的小新
没有蜡笔的小新 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:21

    Often the choice is just one of style - one looks or feels more natural than the other for a particular case.

    There is also the argument that using indexes can cause the compiler to have to repeatedly recalculate offsets inside a loop - I'm not sure how often this is the case (other than in non-optimized builds), but I imagine it happens, but it's probably rarely a problem.

    One area that I think is important in the long run (which might not apply to an introductory C class - but learn 'em early, I say) is that using pointer arithmetic applies to the idioms used in the C++ STL. If you get them to understand pointer arithmetic and use it, then when they move on to the STL, they'll have a leg up on how to properly use iterators.

提交回复
热议问题