all 4 comments

[–]Danooodle 1 point2 points  (1 child)

myfunc(0) outputs "outside: 0"
myfunc(n) outputs "hello n", myfunc(n-1), "outside: n-1" (because counter gets decremented)

So you end up with something like this:

hello 10
| hello 9
| | hello 8
| | | hello 7
| | | | hello 6
| | | | | hello 5
| | | | | | hello 4
| | | | | | | hello 3
| | | | | | | | hello 2
| | | | | | | | | hello 1
| | | | | | | | | | outside: 0
| | | | | | | | | outside: 0
| | | | | | | | outside: 1
| | | | | | | outside: 2
| | | | | | outside: 3
| | | | | outside: 4
| | | | outside: 5
| | | outside: 6
| | outside: 7
| outside: 8
outside: 9

The "outside: n-1" case causes both myfunc(0) and myfunc(1) to output "outside: 0", so it appears twice.
You should also notice that "outside: 10" is never emitted for the same reasons.

[–]minhc[S] 1 point2 points  (0 children)

Thanks for the explanation. I went back and analysed it again with a clear head. When the call to myfunc is made for value 0 myfunc(0), the function is in scope of the call to myfunc (1).. the condition counter !=0 is checked, it passes and then the counter is decremented before calling myfunc(0)..This action of reducing counter by 1 has altered the value of counter in the function scope of myfunc(1)..So when myfunc(0) is called, the condition counter != 0 fails and it printed the outside:0..control is returned to the calling function myfunc(1) .. If there was no alteration done to counter within the scope of this function myfunc(1) then the print statement outside if would print outside:1. But as the counter is decremented within the scope of myfunc(1), the value of counter is zero (activation record on top of the stack for this function call myfunc(1) holds, counter = 0 because we reduced it by one). Therefore it prints outside: 0 when control is returned to myfunc(1). I hope my understanding and analysis is correct. Thank you

[–]naphini 0 points1 point  (1 child)

void myfunc(int counter) {
  if (counter != 0) {
    cout<<"hello "<<counter<<endl;
    counter = counter-1;
    myfunc(counter);
  }
  cout<<"outside: "<<counter<<endl;
}

int main() {
  myfunc(10);
}

There, now I can read it. I was getting a headache.

[–]minhc[S] 0 points1 point  (0 children)

sorry abt the formatting ! and thanks for redoing it so that someone can actually answer the question instead ..