James Kuyper
5/1/2011 10:54:00 AM
On 05/01/2011 05:57 AM, miloody wrote:
> hi:
> On May 1, 5:52�pm, Ike Naar <i...@iceland.freeshell.org> wrote:
>> On 2011-05-01, miloody <milo...@gmail.com> wrote:
>>
>>> � � � � idx0 = (++idx0)%2;
>>
>> The ++ operator has a side effect that makes the statement undefined.
>> Since you're not making use of the side effect, you may as well remove
>> it and simply write:
>>
>> � � � � idx0 = (idx0 + 1) % 2;
> why ++ makes the statement undefined?
Because it's in the same expression with the "=" operator, acting on the
same object, with no sequence points between them. The standard says
"Between the previous and next sequence point an object shall have its
stored value modified at most once by the evaluation of an expression".
Your statement modifies the value of idx0 twice, with no sequence points
anywhere except at the end of the statement.
One reason for this, is that the committee did not want the standard to
specify which order the two assignments occur in - they want to
discourage people from writing code like that. However, if that's all
that mattered, they could simply have left the order unspecified.
For example, in general it's possible that it takes multiple
instructions to update the value of an object (for instance, if it's a
64-bit type on an 8-bit processor). In that case, the instructions
implementing one modification of the object might be interleaved with
the ones that implement another; the result could be just about anything.
> what kind of side effect it will be if I use ++ before parameter?
> thanks for your help,
The C standard classifies the change in the value of idx0 as a
side-effect of the "++" operator. It's also a side-effect of the "="
operator. That may seem to be an odd way of thinking about things, since
that "side-effect" is normally the main reason for using an assignment
operator. However, that's the way the C standard describes these things.
As far as the standard is concerned, the "main effect" (a phrase never
used by the standard) of these expressions is to result in a value which
can be used in yet another expression.
--
James Kuyper