Public Group

[C++]array indexing vs pointer arithmetic

This topic is 3724 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

Recommended Posts

int x[5];
x[4] = 10;
*(x + 4) = 10;


Array indexing has a cleaner syntax but (as I've read) pointer arithmetic is faster. My question is, is it worth to use pointer arithmetic? Is there a noticeable difference?

Share on other sites
AFAIK, they are pretty much the same thing, there's no difference. But if you want to be sure about that, look at the disassembly of both and compare them.

Share on other sites
It isn't faster.

Lets imagine you are writing a compiler. Since the two operations are equivalent, why wouldn't you make them compile to the same assembly?

The only place I use pointer arithmetic is when I am using pointers as iterators. E.g:
int x[5];for(int *ptr = x ; ptr != x + 5 ; ++ptr){   // ...}

Even then, this kind of code is usually wrapper in std::for_each, std::find or std::copy (and so on...).

Share on other sites
In the general case, pointers are slower due to aliasing considerations that prevent optimization.

Note that a is identical to *(a+i) by definition, so neither is faster.

Share on other sites
Quote:
 Original post by sheep19Array indexing has a cleaner syntax but (as I've read) pointer arithmetic is faster.

Where did you read this?

a is only syntactic sugar for *(a+i), that is, the "array indexing operator" as we call it isn't even defined for arrays, only for pointers. In the expression a+i, the array name a decays into a pointer to its first element, then we add i to get to the i-th position, and then we dereference that new pointer to get the element at that position.

If you compile your program with gcc -S and look at the generated assembly, you will notice that a and *(a+i) compile to the exact same code. There is absolutely no difference.

Share on other sites
Quote:
 Original post by ToohrVykIn the general case, pointers are slower due to aliasing considerations that prevent optimization.

This is general recommendation (see 2.2 (pdf)). In practice, there really is no difference, or it is completely compiler dependent.

• What is your GameDev Story?

In 2019 we are celebrating 20 years of GameDev.net! Share your GameDev Story with us.

(You must login to your GameDev.net account.)

• 28
• 16
• 10
• 10
• 11
• Forum Statistics

• Total Topics
634103
• Total Posts
3015539
×