I initially thought that it has a different use for pointers and for arrays. In the former case, it adds whatever is in brackets to the pointer and then dereferences the sum; in the latter case it would just yield the ith element of an array.
Then I realized that an array variable returns the pointer to the first element, so the operator does the same thing in each case: offset and dereference.
Does the bracket [] operator indeed only have a single use in C?
[]
is called array subscript operator, but syntactically it's used on a pointer. An array is converted to a pointer to the first element in this usage (and many others). So, yes, []
is the same for arrays and pointers.
C11 §6.5.2.1 Array subscripting
Constraints
One of the expressions shall have type ‘‘pointer to complete object type’’, the other expression shall have integer type, and the result has type ‘‘type’’.
Semantics
A postfix expression followed by an expression in square brackets
[]
is a subscripted designation of an element of an array object. The definition of the subscript operator[]
is thatE1[E2]
is identical to(*((E1)+(E2)))
. Because of the conversion rules that apply to the binary+
operator, ifE1
is an array object (equivalently, a pointer to the initial element of an array object) andE2
is an integer,E1[E2]
designates theE2
-th element ofE1
(counting from zero).
Whether it does "one thing" depends on what you think "one thing" means.
In C, the operator is defined like so
e1[e2] means *(e1+e2)
That's it. One thing. Or is it? Suppose a
is an array and i
is an integer. We can write:
a[3]
a[i]
3[a]
i[a]
and suppose p
is a pointer and i
is an integer. We can write
p[3]
p[i]
3[p]
i[p]
Arrays or pointers. Two things? Not really. You know that when we use the plus operator where one of the two operands is "an array" you are really doing pointer arithmetic.
The second part of your question - can it be used for things other than pointer arithmetic - is basically no in C, but yes in C++, because in C++ we can overload this operator. However sometimes you will see []
in type expressions, but that is probably not what you are asking about because in that case, we aren't really using it as an operator (we're using it as a type operator, which is different).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With