Page 1 of 1
about (++i)+(++i)
Posted: Wed Jun 09, 2004 7:20 am
by tiaral
(1)
i=0;
a=(++i)+(++i);
then a==4
(2)
i=0;
a=(++i)+(++i)+(++i);
then a==7
(3)
i=0;
a=(++i)+(++i)+(++i)+(++i);
then a==11
i just test this with vc++ 6.0 & gcc 3.2 for win32
i wonder how to explain it.
hmm
Posted: Wed Jun 09, 2004 7:59 am
by shahriar_manzoor
In turbo C++ the values the 4, 9 and 16 respectively which I find consistent with a certain rule.
Re: about (++i)+(++i)
Posted: Wed Jun 09, 2004 10:27 am
by CDiMa
tiaral wrote:(1)
i=0;
a=(++i)+(++i);
then a==4
(2)
i=0;
a=(++i)+(++i)+(++i);
then a==7
(3)
i=0;
a=(++i)+(++i)+(++i)+(++i);
then a==11
i just test this with vc++ 6.0 & gcc 3.2 for win32
i wonder how to explain it.
ANSI C specifies that your examples have undefined behaviour.
The pre-increment operator has two meanings:
- - it returns a value
- as a side effect it increments the variable i
The side effect is guaranteed to be completed only at the next sequence point, which in your example is the semicolon at the end of the expression. Between two sequence points a variable may have its value changed only once. Since your examples change the value of i multiple times their behaviour is undefined.
Look at
this thread for another discussion about side effects and sequence points.
Ciao!!!
Claudio