Path: utzoo!attcan!utgpu!jarvis.csri.toronto.edu!rutgers!haven!mimsy!chris From: chris@mimsy.UUCP (Chris Torek) Newsgroups: comp.lang.c Subject: Re: "abcdef"[3] == 3["abcdef"], but why? Message-ID: <19883@mimsy.UUCP> Date: 29 Sep 89 18:23:05 GMT References: <781@cc.helsinki.fi> Organization: U of Maryland, Dept. of Computer Science, Coll. Pk., MD 20742 Lines: 48 In article <781@cc.helsinki.fi> TEITTINEN@cc.helsinki.fi writes: >Could someone explain to me what a C compiler does when it runs into >expression 3["abcdef"]? 3["abcdef"] is of the form `e1 [ e2 ]' (e1 and e2 are arbitrary expressions). Every C compiler converts this internally to *( (e1) + (e2) ) (actually, compilers need only work *as if* they had done this conversion, although many really do it). So we really have *( 3 + "abcdef" ) To find out what this means, if anything, first try evaluating the expression `3+"abcdef"'. This is + Apply the rule for array objects in rvalue contexts: change `array N of T' to `pointer to T', whose value is the address of the first (0th) element of the array: + We now have an expression of the form +, so we move to the int'th element of the array that starts at *. Here we move to the 3rd element of `abcdef\0', which is the letter `c'. Now we have Now we can put the indirection back: *( ) The operand for `*' is a pointer, so we get the object to which the pointer points: Since e1[e2] is equivalent to *(e1+e2), if we reverse the expressions, the only change is in the order of the operands to `+'. The result of + is the same as that of +, so we wind up with again. -- In-Real-Life: Chris Torek, Univ of MD Comp Sci Dept (+1 301 454 7163) Domain: chris@mimsy.umd.edu Path: uunet!mimsy!chris