Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does the bracket [] operator only have a single use?

Tags:

arrays

c

pointers

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?

like image 267
Wuschelbeutel Kartoffelhuhn Avatar asked Nov 05 '13 04:11

Wuschelbeutel Kartoffelhuhn


2 Answers

[] 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 that E1[E2] is identical to (*((E1)+(E2))). Because of the conversion rules that apply to the binary + operator, if E1 is an array object (equivalently, a pointer to the initial element of an array object) and E2 is an integer, E1[E2] designates the E2-th element of E1 (counting from zero).

like image 178
Yu Hao Avatar answered Nov 15 '22 05:11

Yu Hao


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).

like image 40
Ray Toal Avatar answered Nov 15 '22 04:11

Ray Toal