And now for something completely different. Was: String.join revisited (URGENT for 1.6)

James Logajan JamesL at Lugoj.Com
Fri Jun 2 00:14:44 EDT 2000


Johannes Stezenbach wrote:
> 
> James Logajan <JamesL at Lugoj.Com> wrote:
> >Speaking of interesting syntax, did you know the following is perfectly
> >valid C/C++:
> >
> >var = 2["abc"];
> >
> >Points awarded for determining the type of "var" and the value assigned to
> >it. Extra credit points for explaining why this is valid C/C++. (Hint: this
> >has been valid C for as long as the language has been around.)
> 
> The magic of C pointer arithmetics makes a[i] equivalent to i[a], so
> in the above var is of type char and has a value of 'c'.
> 
> Explanation:
>   After e.g.    char a[] = "abc";
>   the following are true:
>         a == &a[0]
>         *a == a[0]
>         a + i == &a[i]
>         *(a + i) == a[i]
>         *(i + a) == a[i] == i[a]
> 
> The good thing about this is that nobody ever uses it,
> except maybe in obfuscation contests.
> 
> Johannes

You get all available points! Because any combination of expressions e1[e2]
is immediately reduced to *(e1 + e2) by the compiler (by definition) and
because the "+" operator commutes, e1[e2] == e2[e1]. HOWEVER, no equivalent
line of reasoning applies to array declarations. "Type var[size]" can not be
changed to "Type size[var]"; again by definition of the language.


P.S. A friend once pointed out some old code where someone had mapped DOS
drive numbers 0, 1, ... to drive letters 'a', 'b', ... using the simple
expression "abcd"[drive_num].



More information about the Python-list mailing list