C - when to use pointer arithmetic, when to use array indexing?

前端 未结 6 1437
盖世英雄少女心
盖世英雄少女心 2020-12-08 11:38

In C, when is it preferrable to use one over the other?

6条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-08 12:37

    "Array indexing" is just syntactic sugar that wraps "pointer arithmetic". It is purely cosmetic, just another notation, meaning that using one or another would be a matter of personal preference.

    The real question that usually hides behind what you asked is when to use random access and when to use sequential access (with "pointer arithmetic" implying sequential increment/decrement of a pointer by no more than 1). The answer is: prefer to use sequential access when you can, only use random access when you must.

    As long as performance doesn't suffer, it is always a better idea to implement algorithms by relying on the minimal set of requirements. Random access is a stronger requirement than sequential access, meaning that the former should be avoided when reasonably possible.

提交回复
热议问题