Path: utzoo!utgpu!jarvis.csri.toronto.edu!mailrus!ncar!tank!mimsy!chris From: chris@mimsy.UUCP (Chris Torek) Newsgroups: comp.lang.c Subject: Re: Another silly question Message-ID: <17243@mimsy.UUCP> Date: 2 May 89 23:19:10 GMT References: <2459@nmtsun.nmt.edu> <9987@claris.com> <879@twwells.uucp> <17812@cup.portal.com> Organization: U of Maryland, Dept. of Computer Science, Coll. Pk., MD 20742 Lines: 94 In article <17812@cup.portal.com> Tim_CDC_Roberts@cup.portal.com writes: >... let me refer to the oft-used example 2["hello"]. >I agree that this works and is equivalent to "hello"[2]. I've seen it >in books and postings. My simple question is why? The type of "hello" is array 6 of char (or char [6] if you prefer) which, in all contexts except declarations and targets of sizeof(), changes to pointer to char with the value being the address of the first (zero'th) element of the array. So the types of the two expressions "hello"[2] and 2["hello"] are (char *) [ (int) ] and (int) [ (char *) ] The [] syntax means `add the value of the object to the left to the value of the object to the right, then dereference': * ( (char *) + (int) ) and * ( (int) + (char *) ) respectively. Addition is defined on two cases: addition of scalar types with other scalar types (such as int+int, or double+int, or char+long) and addition involving pointers. Both additions involve pointers, so both follow these rules, which are: The result of plus is the address of the N'th object of type T `away from' the place where the pointer points, in the `increasing' direction if N is positive, and the `decreasing' direction if N is negative. The result of plus is the same as that of plus . No other additions involving pointers are legal. >Doesn't that equivalence imply that the pointer type is somehow >"stronger" than the simple type? You might think of it as such; without a defintion of `strength' there is no way to say. >Is a compiler force to examine all of the elements in a pointer >expression and establish the "master type" of the expression? The compiler must look at both types in any dyadic operation (addition, subtraction, multiplication, division, -> selection, . selection, etc.). The result of the lookup can be found in a table in the language definition. >If I mix two pointer types ... is this anarchy? Is it a syntax error? If the operation is addition, it is a semantic error: there is no definition for the result of addition of two pointers. (The subtraction operator allows two operands which are both pointers, but they must have the same type.) >(Please don't submit 30 replies saying "because the book says so"...) s/book/language definition/, and you have the answer above (but without all the verbiage). -- In-Real-Life: Chris Torek, Univ of MD Comp Sci Dept (+1 301 454 7163) Domain: chris@mimsy.umd.edu Path: uunet!mimsy!chris