Path: utzoo!mnetor!uunet!husc6!cmcl2!phri!bc-cis!john From: john@bc-cis.UUCP (John L. Wynstra) Newsgroups: comp.lang.c Subject: Re: Is this a bug, or is it just me? Message-ID: <1050@bc-cis.UUCP> Date: 17 Dec 87 22:04:57 GMT References: <464@ecrcvax.UUCP> Reply-To: john@bc-cis.UUCP (John L. Wynstra) Organization: Brooklyn College of CUNY, Brooklyn, NY Lines: 60 In article <464@ecrcvax.UUCP> johng@ecrcvax.UUCP (John Gregor) writes: > >int a[3] = {1, 4, 16}; >int i = 0; > >main () { > sum = a[i++] + a[i++] + a[i++]; The C compiler is free to implement this as it chooses. It is not a precedence/association question. The K&R text says something about this in re: "a[i] = i++;" Which a[i] is it that is assigned to, a[i] or a[i+1]? Answer: it depends on the compiler. The correct way to do what you want is, sum = a[i] + a[i+1] + a[i+2]; i += 3; > >Am I missing some obscure part of K&R (I've looked). Or is this truly a >bug? > No bug. Just a confusion on your part as to what operator precedence and associativity mean, vs., the runtime order of execution. This is a currently popular one in comp.lang.c. An interesting note is that the comma operator *does* guarantee the order of evaluation, left to right. So, if you think it just wouldn't be proper C if everything weren't all on one line, sum = a[i] + a[i+1] + a[i+2], i += 3; Operator precedence, and associativity (within one level of precedence), determine the syntactic structure of the code. I think of it as a translation of the code into a generalized tree structure. (Of course, an actual tree need not be generated, there are other forms of intermediate structure, and compilers need not conform to this ideal, but this is my mental image.) What you now have is the syntactic structure (terminology borrowed from linguistics) of the sentence (code fragment), not its semantic meaning, ie, we can `parse' the sentence [image taken from English 101: we can diagram the sentence out] but we don't yet know what it all means, *that's* the semantic analysis part of the compilation. The point is that the compiler is free to choose what is meant by such a construction as "i=0, a[i++] + a[i++]"; is it "a[0] + a[1]" or "a[0] + a[0]" or even "a[1] + a[1]" ... ? The choice would seem to be up to the particular way the code generation phase of the compiler works. Or maybe it's just the type of compiler itself, eg, is it LL vs. LR? (or top-down vs. bottom-up?) Eh! I give up. My humble knowledge of compilers is exceeded. Who knows? The meaning should be unequivocably unambiguous. A recommended style of one side-effect per statement (or per comma-separated expression) seems to be in order. --john -- John L. Wynstra US mail: Apt. 9G, 43-10 Kissena Blvd., Flushing, N.Y., 11355 UUCP: john@bc-cis.UUCP { eg, rutgers!cmcl2!phri!bc-cis!john }