• Advertisement
Sign in to follow this  

[C++]array indexing vs pointer arithmetic

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

If you intended to correct an error in the post then please contact us.

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 this post


Link to post
Share on other sites
Advertisement
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 this post


Link to post
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 this post


Link to post
Share on other sites
Quote:
Original post by sheep19
Array 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 this post


Link to post
Share on other sites
Quote:
Original post by ToohrVyk
In 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.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement