Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Both a[i]
and *(a + i)
access the i
th element of array a
.
Are there reasons to prefer one over the other(performance, readability, etc...)?
Neither one is better from a language point of view since they are the same, array indexing should just be syntactic sugar for pointer arithmetic. We can see this from the draft C99 standard section 6.5.2.1
Array subscripting which says (emphasis mine):
[...]The definition of the subscript operator [] is that E1[E2] is identical to (*((E1)+(E2))).[..]
Although for others reading your code a[i]
is probably more readable.
a[i]
should be preferred, because it is more commonly used and so will be understood more quickly by the person reading the code.
Although they are identical in arrays, I prefer a[i] for the following reason. Suppose you have code like this:
double gradient[3];
// 200 lines later
double dx = gradient[0]; // Works fine
double dy = *(gradient + 1); // Works just as well
Then somebody decided that std::vector looks better than double[]:
vector<double> gradient;
// 200 lines later
double dx = gradient[0]; // Still works
double dy = *(gradient + 1); // Ouch!
Then somebody else decided to go object-oriented all the way:
class Gradient
{
public:
double operator[](int index) const;
};
// 1000 lines later
Gradient gradient;
// 200 lines later
double dx = gradient[0]; // Still works
double dy = *(gradient + 1); // Ouch!!!
Thus, from the viewpoint of maintainability, I prefer to say exactly what I mean, without obscuring the intent with context-dependent synonyms. If I mean "take i-th element of a" then I say exactly that in C++ lingo:
a[i];
rather than relying that for the particular implementation of a one can use a fancier expression for the same.
C has no operator overloading. So you are safe to use whichever you want.
I would use a[i]
for clarity when reading the code.
Both are equivalent. Neither one is preferred over other but a[i]
is commonly used by programmers. a[i] = *(a + i) = i[a]
As far as I'm concerned (just finished a C course), there is no difference.
Array is implemented as a pointer to the first element on the stack. So a+1 is just the address on the stack after a :)
Edit:
Also, as mentioned by John Bartholomew, even though they are the same, you might want to use a[i] instead - that is the "normal" way to do it (also in other languages) :)
For readability purposes, I would definitely go with a[i]
.