Problem with post-incrementation

Douglas Stetner stetner at .bnr.ca
Thu Apr 18 11:06:08 AEST 1991


In article <6530 at s3.ireq.hydro.qc.ca> godin at ireq.hydro.qc.ca (Andre Godin 8926) writes:
>
>	Every times I call this function, the value of 'str' 
>	is always tmp_0 and 'i' never gets incremented. If
>	we use the pre-increment operator, the function works 
>	properly. Why post-incrementing doesn't work?
>
>	(I'm using cc under SunOs 4.0.3.)
>
>char *
>fnc() /*
>----- */
>{
>static	int	i = 0;
>static	char	str[256];
>
>	sprintf(str, "tmp_%d", i = (i++) % 3600);
>
>	return (str);
>}

Think about the way this will get compiled
i = (i++) % 3600
      |
      V
i = ( 0 ) % 3600   /* i has been incremented, i = 1 */
          |
	  V
i =       0        /* the assignment takes place and i = 0 */

Pre increment works because it evaluates this way...
i = (++i) % 3600
      |
      V
i = ( 1 ) % 3600   /* i has been incremented, i = 1 */
          |
	  V
i =       1        /* the assignment takes place and i = 1 */

It would be much better to either do the sprintf then twiddle i
or to twiddle i then do the sprintf, as this would be more readable
and will most likley make no difference to the size/speed of the
resulting executable.
not produce 'smaller|quick
--
--------------------------------------------------------------------------------
Douglas G. Stetner, 4S75  |  Bell-Northern Research  | My opinions are my own.
      stetner at bnr.ca      |  P.O. Box 3511, Stn. C   | (613) 828-6321  (home)
 ..!uunet!bnrgate!stetner |  Ottawa, ON, CANADA      | (613) 763-8396  (work)



More information about the Comp.lang.c mailing list