about (++i)+(++i)

Write here if you have problems with your C++ source code

Moderator: Board moderators

Post Reply
tiaral
New poster
Posts: 5
Joined: Sat Feb 14, 2004 5:06 am
Contact:

about (++i)+(++i)

Post 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.
shahriar_manzoor
System administrator & Problemsetter
Posts: 399
Joined: Sat Jan 12, 2002 2:00 am

hmm

Post by shahriar_manzoor »

In turbo C++ the values the 4, 9 and 16 respectively which I find consistent with a certain rule.
CDiMa
Experienced poster
Posts: 214
Joined: Fri Oct 17, 2003 5:49 pm
Location: Genova

Re: about (++i)+(++i)

Post 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
Post Reply

Return to “C++”