Click here to Skip to main content
15,893,487 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi all, can any one help me?
I have this simple program:

#include<iostream.h>
void main()
{
int A,B= 8;
A = ++B + ++B;
cout<<A<<B;
}

I expected that the result of A will be 9+10 = 19 but the result was 20 and I tried many programs but I couldn't understand the reason of their results.

Can any one explain the reasons for me.
thank u for all
Posted
Updated 4-Aug-17 0:01am

The C++ standard (1998) says:

"Between the previous and next sequence point a scalar object shall have its stored value modified at most once by the evaluation of an expression. Furthermore, the prior value shall be accessed only to determine the value to be stored. The requirements of this paragraph shall be met for each allowable ordering of the subexpressions of a full expression; otherwise the behavior is undefined."

As you're modifying the scalar object (B) twice before the next sequence point (the terminating semi-colon) what happens is undefined. When something is undefined all bets are off - the compiler can chuck out any old rubbish it wants. Sometimes the rubbish is what you want but quite often it's not.

Have a read of Angelika Langer's discussion[^] of sequence points for a bit more background.

Cheers,

Ash
 
Share this answer
 
v2
Comments
Richard MacCutchan 11-Oct-10 8:28am    
Elegantly put; I wish I had the patience to read the standard (and the memory to remember it).
You are breaking the rules of C++. Using increment/decrement multiple times in a single expression on the same variable gives results that cannot be guaranteed, as the compiler writer is free to evaluate the expression in any way they see fit. You should use a code block like:
C++
int A,B= 8;
A = ++B;    // A == 9
++B;        // B == 10
A += B;     // A == 19
}
 
Share this answer
 
Have you tried bracketing the formula ie. :
A = (B++) + (B++)
 
Share this answer
 
You are using the pre-increment, then the increments on your variable are done the same way as they are written on a separate statement, before than the current one. In other words, this line:

C++
int A, B = 8;
A = ++B + ++B;


is treated by the compiler in the same way than:

C++
int A, B = 8;
B = B + 1;
B = B + 1;
A = B + B;
 
Share this answer
 
write A=(++B)+(++B);

or

:rose:
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900