Path: utzoo!utgpu!news-server.csri.toronto.edu!rpi!zaphod.mps.ohio-state.edu!uakari.primate.wisc.edu!caen!uwm.edu!ogicse!vegdahl From: vegdahl@ogicse.ogi.edu (Steve Vegdahl) Newsgroups: comp.lang.c Subject: Re: Problem with post-incrementation Message-ID: <20095@ogicse.ogi.edu> Date: 16 Apr 91 13:35:34 GMT References: <6530@s3.ireq.hydro.qc.ca> Organization: Oregon Graduate Institute (formerly OGC), Beaverton, OR Lines: 42 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); >} 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.