gam@proper.UUCP (Gordon Moffett) (01/12/84)
Recently I came across the following code fragment:
char *cp, ch[10];
unsigned u;
.
.
for (cp = ch; u != 0; u >>=4) {
*cp++ = "0123456789ABCDEF"[u & 0xF];
}
Shocking isn't it? But the subscripting of the constant array is
legal K&R syntax (see sec 7.1), so this does work on all valid compilers.
As a stylistic note, I would suggest putting the string in parentheses
to emphasize its use as an expression:
*cp++ = ("0123456789ABCDEF")[u & 0xF];
This made it clearer to me, anyway (former APL hacker...).
ucbesvax.turner@ucbcad.UUCP (01/15/84)
#R:proper:-83400:ucbesvax:4800032:000:678 ucbesvax!turner Jan 14 12:23:00 1984 re: subscripting constant arrays . Not only can you say "0123"[i], and the like, but sizeof ("0123") reliably returns 5 (not 4--think.) This is even useful, occasionally--as when you wish to test if the first few chars of a string match some literal constant string. Example: #define MATCH(s,sc) (strncmp (s, sc, sizeof(sc)-1) == 0) if (MATCH (s, "add")) ... then becomes if (strncmp (s, "add", 3) == 0) Here, of course, if sc is not a literal or constant string, sizeof (sc) becomes sizeof (char *). The ideal MATCH macro would detect this and generate cc-warning code instead, but I'm not quite sure how to do that. --- Michael Turner (ucbvax!ucbesvax.turner)
mrm@datagen.UUCP (01/15/84)
Of course it is legal, and is used quite frequently, usually in conversion routines. If you didn't like "0123456789ABCDEF"[i], did you know that: i["0123456789ABCDEF"] is also legal and does the same thing. Michael Meissner Data General Corporation ...{allegra, decvax!ittvax, rocky2}!datagen!mrm