Access operator example:
void print_elements ( int * arr, int n )
{
for (int k = 0; k < n; ++k) printf("%d\n", arr[k]);
}
Pointer arithmetic example:
void print_elements ( int * arr, int n )
{
for (int * pa(arr), * pb(arr+n); pa != pb; ++pa) printf("%d\n", *pa);
}
The second involves 2 variables for the loop, pa
and pb
, whereas the first only involves 1 extra variable, k
. Then again, in the second you're doing
increment pa by 1, dereference
whereas in the first one you're doing
increment k by 1, add k to the pointer arr, derefence
so that the first one uses fewer operations to iterate through the loop.
All things considered, which is faster? Is the comparator <
faster than !=
for integral types? Using <
seems "safer" since there's always that irrational fear that having something like pa != pb
as a condition fail because pa
could jump over pb
if the algorithm inside the loop is reconstructed. Is incrementing a pointer by 1
generally faster than incrementing it by something greater than 1
? I want to consider everything possible.