Problem with post-incrementation

Jim Giles jlg at cochiti.lanl.gov
Tue Apr 16 03:26:28 AEST 1991


	sprintf(str, "tmp_%d", i = (i++) % 3600);

I have seen this bug in a number of C programs (including the _second_
edition of a published book on graphics in C).  It is one of the
drawbacks of side-effect operators that such errors are made and
remain undetected.

The problem is that i = (i++) etc.  assigns the value of the expression
to the variable i.  Depending on the order that the side-effects are
carried out, this may happen before or after the side-effect for the
incrementation operator.  If the assignment happens _after_ the increment,
then i will get zero every time.  What you want to do is this:

      sprintf(str, "tmp_%d", i = (i+1) % 3600);

You only need i to be assigned once anyway.

J. Giles



More information about the Comp.lang.c mailing list