Skip to the task
Layout
Back to classic view

You are looking ahead. Your place is still task 1: Functions.

CHECKTask 21 of 23 · step 8: Extra: how does the CPU see it?

How does assert know the line?

When the assert in digit_sum fails, the message has the file name and line 8. Where do they come from?

Stuck?

The compiler writes them in as constants: mov r8d, 8 and the string "practice/05/recursion.c" among the constants at the top. They are passed to _assert only when the condition is not met. # ── topic 6 (lesson 43, step 11): practice/06/search.c ──────────────

Extra · x86-64 · Intel syntax · Windows (MinGW GCC)

-O0 -O1

C source recursion.c

#include <assert.h>
#include <stdio.h>
/* The digit sum; depth is how many calls deep the function already is.
Before: n >= 0, depth >= 0.
After: the sum of the digits of n. */
int digit_sum(int n, int depth) {
assert(n >= 0 && depth >= 0);
printf("%*sdigit_sum(%d)\n", depth * 2, "", n);
if (n < 10) {
return n;
}
return n % 10 + digit_sum(n / 10, depth + 1);
}
/* n! = 1 * 2 * ... * n.
Before: n is from 0 to 20 (21! doesn't fit in a long long).
After: the factorial of n; 0! = 1. */
long long factorial(int n) {
assert(n >= 0 && n <= 20);
if (n == 0) {
return 1;
}
return n * factorial(n - 1);
}
int main(void) {
int sum = digit_sum(472, 0);
printf("Digit sum: %d\n", sum);
printf("5! = %lld\n", factorial(5));
printf("20! = %lld\n", factorial(20));
return 0;
}

x86-64 assembly -O1

.LC0:
.ascii "practice/05/recursion.c\0"
.LC1:
.ascii "n >= 0 && depth >= 0\0"
.LC2:
.ascii "\0"
.LC3:
.ascii "%*sdigit_sum(%d)\12\0"
digit_sum:
push rsi
push rbx
sub rsp, 40
mov ebx, ecx
mov esi, edx
test ecx, ecx
js .L7
test edx, edx
js .L7
.L4:
lea edx, [rsi+rsi]
mov r9d, ebx
lea r8, .LC2[rip]
lea rcx, .LC3[rip]
call printf
cmp ebx, 9
jg .L9
.L6:
mov eax, ebx
add rsp, 40
pop rbx
pop rsi
ret
.L7:
mov r8d, 8
lea rdx, .LC0[rip]
lea rcx, .LC1[rip]
call [QWORD PTR __imp__assert[rip]]
jmp .L4
.L9:
lea edx, 1[rsi]
movsx rsi, ebx
imul rsi, rsi, 1717986919
sar rsi, 34
mov eax, ebx
sar eax, 31
sub esi, eax
mov ecx, esi
call digit_sum
mov edx, eax
lea eax, [rsi+rsi*4]
add eax, eax
sub ebx, eax
add ebx, edx
jmp .L6
.LC4:
.ascii "n >= 0 && n <= 20\0"
factorial:
push rbx
sub rsp, 32
mov ebx, ecx
cmp ecx, 20
ja .L16
mov eax, 1
test ecx, ecx
jne .L12
.L10:
add rsp, 32
pop rbx
ret
.L16:
mov r8d, 20
lea rdx, .LC0[rip]
lea rcx, .LC4[rip]
call [QWORD PTR __imp__assert[rip]]
.L12:
lea ecx, -1[rbx]
call factorial
mov rcx, rax
movsx rax, ebx
imul rax, rcx
jmp .L10
.LC5:
.ascii "Digit sum: %d\12\0"
.LC6:
.ascii "5! = %lld\12\0"
.LC7:
.ascii "20! = %lld\12\0"
main:
sub rsp, 40
call __main
mov edx, 0
mov ecx, 472
call digit_sum
mov edx, eax
lea rcx, .LC5[rip]
call printf
mov ecx, 5
call factorial
mov rdx, rax
lea rcx, .LC6[rip]
call printf
mov ecx, 20
call factorial
mov rdx, rax
lea rcx, .LC7[rip]
call printf
mov eax, 0
add rsp, 40
ret