You will find that
[ ] is among the
higher priority operators
As I have said so many times:
An operator (in any programming language)
will returnsomething
(It can be an value
(e.g.: 3 + 4) and it can be
a variable
(e.g.: *p)
The effect of the
[ ] operator
Fact:
The [ ] operator can
only be
applied to a
reference typed value
(i.e. a pointer or an address)
Syntax of the [ ]
operator:
p [ i ]
where:
p is a reference typed expression
i is an integer typed expression
meaning of the
[ ] operator:
p [ i ] <===> *(p + i)
Note:
You have already learned/seen about
pointer arithmentic, so
you should know what
*(p + i) mean !!!
You can view the [ ]
operator as a
shorthand notation
to replace 2 operaions
(* and +)
Note:
The [ ] operator can work with
a constant of
a reference type.
Example:
double x[10]; // Defines an array
x == &x[0] // x is a constant reference (address)
x[i] == *(x + i) // x[i] selects the i-th element in array x
The [ ] operator can
also be applied to a
reference typed variable p
!!!
The
C compiler will
translate:
translates to
p[ index ] ====> *(p + index)
Example:
double x[10]; // Defines an array
double *p; // p is a reference variable
p == &x[2] // p is a variable of a reference (address) type
p[i] == *(p + i) // x[i] selects the (i+2)-th element in array x !!
Common use of the
[ ] operator:
Instead of using
(*p + i)
to access the
i^{th}array element in a
dynamic array, we can
now use:
p[i]
(This looks a whole lot sexier
and a lot more like an
ordinary array)