[Subject Prev][Subject Next][Thread Prev][Thread Next][Subject Index][Thread Index]

Re: i = i++

On Thu, Jan 11, 2001 at 08:49:12AM +0530, Amarendra GODBOLE typed:
> On Wed, Jan 10, 2001, the greycells of P k j ~ c K expressed:
> > read some C faqs . they say  changing a variable in a statement which refers it twice isn't valid . so
> The question of valid or invalid does not figure out here. The fact is that, the ANSI standard says
> nothing about such statements, these are called "statements with side-effects".
> The outcome is not predictable, as EVERY compiler is free to implement it as it wishes.
> Essentially, K&R advises to avoid such statements with side effects. It is _NOT_ a good programming
> practice at all.

A few days back exactly the same discussion came up in the 
comp.lang.java.programmer newsgroup and there were some interesting comments
about how Java & C treat such constructs.

1) The priority of evaluation is clearly defined and predictable in
   Java. As per the Java language specifications an operation's operands
   are fully evaluated first with the left hand side first and then the
   right hand side. Then only the assignment is performed. So i++ increments
   i, but returns  the pre-incremented value which is then assigned to
   i. So "i" remains unchanged after the operation i=i++;
2) In C & C++ the result is undefined which means results can vary depending
   on compiler implementations. A few comments in the newsgroup discussion 
   went like

<Quote #1 - Dale King>   
In ANSI C it is undefined, which is worse than not specified. In ANSI C
anything could happen including crashing the machine or formatting your hard

<Quote #2 - John Skeet>
Perhaps it would be better if it were actually *defined* to reformat
your hard disk - then people would *certainly* be discouraged from using
it in the name of brevity :)

> People administering C language tests should avoid asking such questions, as they make no sense. ;-)
> (We have a tendency to make the C test as arcane as possible) ;-) 

IMO people who ask such questions in C language tests deserve to be sent to a
firing squad. :)