Problem with post-incrementation

Steve Vegdahl vegdahl at ogicse.ogi.edu
Tue Apr 16 23:35:34 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);
>}

The problem is that the expression
  i = (i++) % 3600)
applies two side-effects to the variable i, without any intevening "sequence
points".  This results in "undefined behavior", according to the ANSI standard.
(Just be glad that it didn't erase your disk!)

Even disregarding ANSI, there are two natural interpretations of the above,
depending on the order chosen by the compiler for the application of the
side-effects to i:
  #1: evaluate "i % 3600"; assign %-result to i; increment i; yield %-result
      as value of expression
  #2: evaluate "i % 3600"; increment i; assign %-result to i; yield %-result
      as value of expression
In the second case, the value of i will remain at 0.

I think what you really want is
	sprintf(str, "tmp_%d", (i++) % 3600);
though this will still likely lead to unexpected behavior if/when i overflows.

		Steve Vegdahl
		Adaptive Solutions, Inc.



More information about the Comp.lang.c mailing list