Sign in to follow this  
sheep19

[C++]array indexing vs pointer arithmetic

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
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[i] 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[i] 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

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this