My questions are as follows:
#include
using namespace std;
inline void print(char a,char b){
cout<"<}
void test(int n,char c1,char c2,char c3){
if(n==1) print(c1,c3); // Here c3 is 'B'. Why is this so? c3 should be equal to 'C'.
else{
test(n-1,c1,c3,c2); // Note:Here c3 and c2 swapped positions.
print(c1,c3); // Here returned to normal.
}
}
int main(){
test(2,'A','B','C');
return 1;
}
Its results are:
A->B
A->C
I think the result should be:
A->C
A->C
Thank.

VulpesPosted Jan 12, 2014, 10:17 AM
n = 2
c1 = 'A'
c2 = 'B'
c3 = 'C'
As n == 2, then test(1, 'A', 'C', 'B') is invoked recursively. In the recursive function call:
n = 1;
c1 = 'A'
c2 = 'C'
c3 = 'B'
So, when print(c1, c3) is called, we get A->B printed to the console.
The stack then unwinds back to the original call of the test function and the line print(c1, c3) is executed. In this call, we have the original parameter values of c1 ='A', c2 = 'B', c3 = 'C' and so we get A->C printed to the console.
The essential point here is that every function call has its own stack frame and therefore its own copy of the parameters.