1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | #include <stdio.h> size_t st; void PrintStackTop(const char *type) { int stack_top; if(st == 0) st = (size_t) &stack_top; printf("In %s call version, the stack top is: %lu\n", type, (st - (size_t) &stack_top)); } int TailCallFactorial(int n, int a) { PrintStackTop("tail"); if(n < 2) return a; return TailCallFactorial(n - 1, n * a); } int NormalCallFactorial(int n) { PrintStackTop("normal"); if(n < 2) return 1; return NormalCallFactorial(n - 1) * n; } int main(int argc, char *argv[]) { st = 0; printf("%d\n", TailCallFactorial(5, 1)); st = 0; printf("%d\n", NormalCallFactorial(5)); return 0; } |
I2luY2x1ZGUgPHN0ZGlvLmg+CgpzaXplX3Qgc3Q7Cgp2b2lkIFByaW50U3RhY2tUb3AoY29uc3QgY2hhciAqdHlwZSkKewogICAgaW50IHN0YWNrX3RvcDsKICAgIGlmKHN0ID09IDApIHN0ID0gKHNpemVfdCkgJnN0YWNrX3RvcDsKICAgIHByaW50ZigiSW4gJXMgY2FsbCB2ZXJzaW9uLCB0aGUgc3RhY2sgdG9wIGlzOiAlbHVcbiIsIHR5cGUsIChzdCAtIChzaXplX3QpICZzdGFja190b3ApKTsKfQoKaW50IFRhaWxDYWxsRmFjdG9yaWFsKGludCBuLCBpbnQgYSkKewogICAgUHJpbnRTdGFja1RvcCgidGFpbCIpOwogICAgaWYobiA8IDIpCiAgICAgICAgcmV0dXJuIGE7CiAgICByZXR1cm4gVGFpbENhbGxGYWN0b3JpYWwobiAtIDEsIG4gKiBhKTsKfQoKaW50IE5vcm1hbENhbGxGYWN0b3JpYWwoaW50IG4pCnsKICAgIFByaW50U3RhY2tUb3AoIm5vcm1hbCIpOwogICAgaWYobiA8IDIpCiAgICAgICAgcmV0dXJuIDE7CiAgICByZXR1cm4gTm9ybWFsQ2FsbEZhY3RvcmlhbChuIC0gMSkgKiBuOwp9CgoKaW50IG1haW4oaW50IGFyZ2MsIGNoYXIgKmFyZ3ZbXSkKewogICAgc3QgPSAwOwogICAgcHJpbnRmKCIlZFxuIiwgVGFpbENhbGxGYWN0b3JpYWwoNSwgMSkpOwogICAgc3QgPSAwOwogICAgcHJpbnRmKCIlZFxuIiwgTm9ybWFsQ2FsbEZhY3RvcmlhbCg1KSk7CiAgICByZXR1cm4gMDsKfQo=
prog.c: In function ‘PrintStackTop’: prog.c:9: warning: format ‘%lu’ expects type ‘long unsigned int’, but argument 3 has type ‘size_t’
-
upload with new input
-
result: Success time: 0s memory: 1720 kB returned value: 0
In tail call version, the stack top is: 0 In tail call version, the stack top is: 0 In tail call version, the stack top is: 0 In tail call version, the stack top is: 0 In tail call version, the stack top is: 0 120 In normal call version, the stack top is: 0 In normal call version, the stack top is: 0 In normal call version, the stack top is: 0 In normal call version, the stack top is: 0 In normal call version, the stack top is: 0 120


