Liverpool_fan
Sami Hyypiä, LFC legend
Re: Post ur C/C++ Programs Here
Old quotes but well...
Though it will work well in MOST compilers though. But C Programmers should avoid tricks such as these in real world.
The correct method is:
But that will work ONLY for integers.
Old quotes but well...
While this solution is impressive, got to say gcc -Wall would give a warning about "undefined behaviour" and that's due to the fact that a is being initialized at the same time and also used between sequence points.Easy. Check this out.
EDIT : Output :-Code:#include<iostream> using namespace std; main() { int a, b; cout << "Enter A and B" << endl; cout << "a = "; cin >> a; cout << endl << "b = "; cin >> b; a = ((b - a) + (b = a)); cout << endl << "a = " << a << endl; cout << "b = " << b; return 0; }
Code:EXECUTING: /home/aditya/test ---------------------------------------------- Enter A and B a = 12 b = 23 a = 23 b = 12 ---------------------------------------------- Program exited successfully with errcode (0) Press the Enter key to close this terminal ...
Though it will work well in MOST compilers though. But C Programmers should avoid tricks such as these in real world.
This expression is undefined in C. This code will modify variable a twice between sequence points and hence it falls in undefined domains of behaviour in C. (Though it works well)Temptation. It's here :- a^=b^=a^=b
The correct method is:
Code:
a ^= b;
b ^= a;
a ^= b;
But that will work ONLY for integers.