Swap the values of 2 int variables

Is there an easy was to swap the values of two variables.... I'm doing it the hard way , but there must be a faster, more efficient way.

And on the same subject, If I call a function, how do I return multiple variables to the calling code.

I'm doing it the hard way ,

Which is what? XOR? Temporary variable?

If I call a function, how do I return multiple variables to the calling code.

Via a struct, via pointers or via references.

TolpuddleSartre:

I have found my answer, was searching for the wrong things…

void swapInt(int*a, int *b) {
int c = *a;
*a = *b;
*b = c;
}

… and it is not homework…

``````void swapInt(int*a, int *b) {
int c = *a;
*a = *b;
*b = c;
}
``````

That's the pointer way, sooo very C.

Now try the reference way - much more C++.

daba: I have found my answer, was searching for the wrong things...

void swapInt(int*a, int *b) { int c = *a; *a = *b; *b = c; }

... and it is not homework....

Much better done using references instead of pointers:

``````void swapInt(int &a, int &b) {
int c = a;
a = b;
b = c;
}
``````

Regards, Ray L.

...and now try without the temporary variable. 8)

TolpuddleSartre: ...and now try without the temporary variable. 8)

No thanks, I'm moving on to other problems to solve....

So what's the advantage of reference over pointers?

sterretje: So what's the advantage of reference over pointers?

More natural - instead of `swap (&a, &b);` you can write `swap (a, b);`

OK, can I have arrays of references?

Note that I'm a C programmer pur sang and only two years ago started embracing C++.

sterretje: OK, can I have arrays of references?

Nope.

TolpuddleSartre: Nope.

Thanks.

sterretje: So what's the advantage of reference over pointers?

TolpuddleSartre: More natural ...

That's a subjective statement. It's not to me. And, I'd imaging that the machine code produced is identical. So, my (subjective) answer in this case would be 'minimal'.