calculation

Hey everyone I am really new to C++, I was wondering how I could make this code simpler.Thank you
1
2
3
4
5
6
void calculate(int x, int y)
{
x = y − x;
y = y − x;
x = y ‚+ x;
}
well, this code there doesn't really do anything (that is, calling calculate() in any other function would do nothing), but
1
2
3
4
//assume x = a; y = b, then
x = y - x; //x = b-a; y = b
y = y - x; //x = b-a; y = a
x = y + x; //x = b; y = a; 

so this swaps two integers.
a better way would be std::swap(a, b);
That doesn't even swap them (the original code, that is). You would have to make the inputs references to do that.

On making THAT particular code shorter (not replacing it), I recommend you look into: http://www.cplusplus.com/doc/tutorial/operators/ (Compound assignment)
ok, thanks for the replys i have one more question.
would x=y-x;be 2*x==yam i right?
No, not at all.

x=y-x would assign y-x to the the variable x.
2*x == y is a comparison, it is true with 2*x equals y.
so just 2*x=y right?
Algebraically, yes. But code-wise, it's as hanst99 says.
Thank you
Topic archived. No new replies allowed.