GeeksforGeeks » C/C++ Programming Questions
value substitution
(3 posts)-
This statement swaps the values in a and b :
b=a+b-(a=b);
can anyone plz explain the steps involved in the execution of this statement...
I guessed a=b would be executed first since it is inside brackets.. then the statement will become :
b=a+b-b; But a=b has been executed so variable a is supposed to contain the value of b & it would be like :
b=b+b-b; //But this doen't happenInstead values of a & b are swapped.. Please explain steps involved int the execution of the statement
-
hello guys....
At very first a=b is evaluated as a is inside da bracketnow value of a becomes = b...now as against dis....
a's value in 1st case is da previous one....soit is evaluated as
b=10 +20(a=20);...if a and b have 10 n 20 values respectively...... thus da answer -
By using visual studio 2010, below program gives me o/p as "20 20".
int _tmain(int argc, _TCHAR* argv[])
{
int a=10, b=20;
b=a+b-(a=b);
cout << a << " " << b;
return 0 ;
}The behavior of the above statement is undefined. Which means swapping behavior may not be achieved in all platforms. It is something to do with sequence points in C and C++. Check below link for the more information about the sequence points.
http://en.wikipedia.org/wiki/Sequence_point
Reply
You must log in to post.