DaniWeb IT Discussion Community

DaniWeb IT Discussion Community (http://www.daniweb.com/forums/index.php)
-   C++ (http://www.daniweb.com/forums/forum8.html)
-   -   array indexing vs pointer arithmetic (http://www.daniweb.com/forums/thread156192.html)

minas1 Nov 9th, 2008 7:54 am
array indexing vs pointer arithmetic
 
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?

ddanbe Nov 9th, 2008 8:27 am
Re: array indexing vs pointer arithmetic
 
Quote:

Array indexing has a cleaner syntax
You said it yourself! So why bother and make your life difficult. When you come back later to your code it will be more easy to understand then if you used pointer arithmetic. If you have a good C++ compiler he would translate both options the same way!

minas1 Nov 9th, 2008 8:31 am
Re: array indexing vs pointer arithmetic
 
Alright, thanks! :)

Narue Nov 9th, 2008 10:29 am
Re: array indexing vs pointer arithmetic
 
>but (as I've read) pointer arithmetic is faster
Prove it. In your example, the two are quite likely compiled to exactly the same machine code. Array subscripting is literally syntactic sugar for the equivalent pointer offset calculation. A more likely example is this:
int x[N];
int *p = x;

for ( int i = 0; i < N; i++ )
  process ( x[i] );

for ( int i = 0; i < N; p += i )
  process ( *p );
The latter could very well be faster (though I would question why you're worried about such micro-optimizations) due to the fact that the body of the loop is only performing a dereference rather than an addition and a dereference.

My advice is not to worry about it. Use whichever more clearly displays your intentions.

ArkM Nov 9th, 2008 10:40 am
Re: array indexing vs pointer arithmetic
 
From the C++ Standard:
Quote:

The expression E1[E2] is identical (by definition) to *((E1)+(E2)).
Sometime pointer arithmetics code is evidently cleaner than "subsripted" one:
int countDigits(const char* str)
{
    int n = 0;
    if (str)
    while (int c = *str++)
        if (c >= '0' && c <= '9')
            ++n;
    return n;
}
Sometimes we have no choice: as usually (but not always) pointer arithmetics code is faster than "subscripted" one on embedded systems where we (often) must save on every microsecond...

It's a far-fetched problem. It's not a language problem...


All times are GMT -4. The time now is 7:04 am.

Forum system based on vBulletin Copyright ©2000 - 2009, Jelsoft Enterprises Ltd.
©2003 - 2009 DaniWeb® LLC