Path: utzoo!utgpu!cunews!bnrgate!bwdls58!!stetner From: stetner@.bnr.ca (Douglas Stetner) Newsgroups: comp.lang.c Subject: Re: Problem with post-incrementation Message-ID: <6509@bwdls58.bnr.ca> Date: 18 Apr 91 01:06:08 GMT References: <6530@s3.ireq.hydro.qc.ca> Sender: news@bwdls58.bnr.ca Reply-To: stetner@bwdlh507.bnr.ca (Douglas Stetner) Organization: Bell-Northern Research, Ltd. Lines: 49 In article <6530@s3.ireq.hydro.qc.ca> godin@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@bnr.ca | P.O. Box 3511, Stn. C | (613) 828-6321 (home) ..!uunet!bnrgate!stetner | Ottawa, ON, CANADA | (613) 763-8396 (work)