5[array] (was Re: "for" loops in C ...)

Ray Butterworth rbutterworth at watmath.waterloo.edu
Tue Nov 8 05:03:54 AEST 1988


In article <1076 at dukeac.UUCP>, sbigham at dukeac.UUCP (Scott Bigham) writes:
> a[b] looks like an array reference, so, naive programmer that I am, I assume
> that it _is_ an array reference.  In particular, I assume that a is an array
> and b is an index into that array.  Something that does otherwise is less
> readable to me, and I suspect I'm not alone.
> 
> The point is, is there ever any practical reason to use this construct?  Do
> you ever use it?  Does anyone?

One use I've seen is to have:
    extern int **pointer;
    index[*pointer]
instead of:
    (*pointer)[index]
It saves two keystrokes :-).

Another, slightly more reasonable, is in treating an array like a
structure and the [] like function or macro invocation:
    typedef int Date[6];
    #define YEAR 0
    #define MONTH 1
    ...
    extern Date table[3];

    YEAR[table[2]] = 1986;
is slightly more readable than:
    table[2][YEAR] = 1986;

Of course it would probably be better to:
    #define YEAR(x) (x)[0]
    YEAR(table[2]) = 1986;
or even better to:
    typedef struct { int year; int month; ... } Date;
    table[2].year = 1986;
but code that used the YEAR[table[2]] form tended to be ported
from B, which has neither macros nor structures.

In any case, the compiler should generate identical code for
all of these.  It's simply a matter of style, and while there
are many wrong styles, there really isn't any one right style.



More information about the Comp.lang.c mailing list