#include <iostream>
using namespace std;
template <class T>
void swap1(T& a, T& b) {
T c = a;
a = b;
b = c;
}
int main() {
int n1 = 5;
int n2 = 7;
swap1(n1, n2);
cout << n1 << " " << n2 << endl;
int *p1 = &n1;
int *p2 = &n2;
swap1(*p1, *p2);
cout << n1 << " "<< n2 << endl;
}
In many languages, when you call a function, you first evaluate its arguments, and then apply the function to the results of the evaluation.
If we follow this rule here however, swap1(n1, n2)
and swap1(*p1, *p2)
would both evaluate to swap1(5, 7)
which makes no sense.
So, what are the rules of evaluation in this case? Also, what are the rules of evaluating a function in general in C++?