Extra: how does the CPU see it?
Extra. Not graded. What happens when a function is called, and when it calls itself?
Open the tool window's Assembly tab. On the left is your practice/05/recursion.c.
A call
call digit_sumgoes to the start of the function and remembers where to come back;retat the end of the function goes back.- Arguments travel in registers:
ninecx,depthinedx. The result comes back ineax. At -O0, both arguments are copied into memory at the start of the function (mov DWORD PTR 16[rbp], ecx): that is topic 5's "a parameter is a copy". - Every call starts with
push rbp,mov rbp, rsp,sub rsp, 40: it makes its own room on the stack. A recursive call is the samecall, only into the same function, so every depth gets its own room. Without a base case, the stack would run out of room in the end.
What to notice (-O0)
return n % 10 + digit_sum(n / 10, depth + 1);first computesn % 10and keeps it inebx, then calls, and adds it once the call returns:add eax, ebx.- There is no division for
n / 10: instead, animulby the odd number 1717986919 and shifts. Multiplying is faster than dividing, and for integers the result is exactly the same. assertis a plainif: a comparison and, when the condition is not met, a call to_assert(in the assembly__imp__assert: the function sits in a Windows DLL) with the file name and the line number (mov r8d, 8). That is where "Assertion failed … line 8" comes from.
Switch to -O1: factorial keeps n in the register ebx, which a call leaves unchanged, and multiplies only once the recursive call has returned.
In CLion's debugger
CLion shows the same machine code. Put a breakpoint on the return line of digit_sum and start Debug. In the Debug window open the GDB tab (the debugger's console) and type, once per debug session:
set disassembly-flavor intel
Then right-click the top line of the Frames list and choose Disassemble: Intel syntax, as here. Your CLion compiles with GCC 11.2, not with the version that made this view, so some instructions may differ slightly.
Optional. The repository's .gdbinit gives the same command at every start, but GDB reads it only if you allow it (README.md says how). The command in the GDB tab always works.