Flow of C++ code | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Flow of C++ code

Can someone explain the flow of this C++ code? I am having trouble understanding the flow, and why it flows the way it does. #include <iostream> using namespace std; void func(int x) { if (x > 0) { func(--x); cout << x; } else { return; } } int main() { func(5); return 0; }

29th Jan 2021, 8:27 PM
Edward Finkelstein
Edward Finkelstein - avatar
3 Answers
+ 3
/* If you unwrap all the calls to func(5), it works very similar to this inline code: */ #include <iostream> using namespace std; int main() { int x=5; --x; { int x=4; --x; { int x=3; --x; { int x=2; --x; { int x=1; --x; { int x=0; } cout<<x; //0 } cout<<x; //1 } cout<<x; //2 } cout<<x; //3 } cout<<x; //4 return 0; } /* The if statement that is used in the recursive function is there to determine when to stop nesting the calls and to start backing out. In this case, when x<=0. */
29th Jan 2021, 9:21 PM
Brian
Brian - avatar
+ 3
Some answers from this stackoverflow thread might help ! https://stackoverflow.com/questions/53022298/why-recursion-occurs-in-reverse#:~:text=This%20happens%20because%20each%20function,get%20printed%20in%20reverse%20order.
29th Jan 2021, 8:52 PM
Abhay
Abhay - avatar
+ 1
Brian, this is really neat, thanks! I think this is the most logical way to think about it, in code blocks.
29th Jan 2021, 10:04 PM
Edward Finkelstein
Edward Finkelstein - avatar