Path: utzoo!utgpu!jarvis.csri.toronto.edu!mailrus!ukma!xanth!kremer From: kremer@cs.odu.edu (Lloyd Kremer) Newsgroups: comp.lang.c Subject: Re: Another silly question Message-ID: <8717@xanth.cs.odu.edu> Date: 2 May 89 16:37:04 GMT References: <2459@nmtsun.nmt.edu> <9987@claris.com> <879@twwells.uucp> <17812@cup.portal.com> Organization: Old Dominion University, Norfolk, Va. Lines: 45 In article <17812@cup.portal.com> Tim_CDC_Roberts@cup.portal.com writes: >In regards to "a[i] == *(a+i) == *(i+a) == i[a]", 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? >......... >Is a compiler force to examine all of the >elements in a pointer expression and establish the "master type" of the >expression? If I mix two pointer types, as in > char * c; > long * ell; > return c + ell; >is this anarchy? Is it a syntax error? What is sizeof(*(c+ell))? Anarchy? Yes, pointer addition has never been defined in C. Syntax error? I guess so. Lint says, "operands of + have incompatible types." Sizeof? The expression is not defined, so its size certainly is not. As to the conceptual implementation of a[i], the compiler sees a pointer a, and an int i. As has been shown, it does not matter which is in the brackets and which is outside. It does matter which is the pointer and which is the integer, but since C is a type-oriented language, it does know this. Many compilers immediately translate a[i] into *(a + i). (Yet another demonstration of their equivalence!) a+i is an address which is evaluated as: {machine address referenced by "a"} plus {"i" times sizeof(*a)}. a[i] or *(a + i) is then the object of type *a located at that address. Although 2["hello"] is cryptic, a compiler *should* get it right according to the language definition (old or new). If I observed a certain compiler to fail on it, my confidence in that compiler to perform properly in other areas would decrease by several orders of magnitude. Another of these "confidence-diminishing" tests is 'sizeof("string")'. The correct answer is 7. Compilers that say 'sizeof(char *)' are broken. -- Lloyd Kremer Brooks Financial Systems ...!uunet!xanth!brooks!lloyd Have terminal...will hack!