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 38 39 | #include <iostream> using namespace std; size_t st; void PrintStackTop(const std::string &type) { int stack_top; if(st == 0) st = (size_t) &stack_top; cout << "In " << type << " call version, the stack top is: " << (st - (size_t) &stack_top) << endl; } int TailCallFactorial(int n, int a = 1) { 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; cout << TailCallFactorial(5) << endl; st = 0; cout << NormalCallFactorial(5) << endl; return 0; } |
I2luY2x1ZGUgPGlvc3RyZWFtPgoKdXNpbmcgbmFtZXNwYWNlIHN0ZDsKCnNpemVfdCBzdDsKCnZvaWQgUHJpbnRTdGFja1RvcChjb25zdCBzdGQ6OnN0cmluZyAmdHlwZSkKewogICAgaW50IHN0YWNrX3RvcDsKICAgIGlmKHN0ID09IDApIHN0ID0gKHNpemVfdCkgJnN0YWNrX3RvcDsKICAgIGNvdXQgPDwgIkluICIgPDwgdHlwZSA8PCAiIGNhbGwgdmVyc2lvbiwgdGhlIHN0YWNrIHRvcCBpczogIiA8PCAoc3QgLSAoc2l6ZV90KSAmc3RhY2tfdG9wKSA8PCBlbmRsOwp9CgppbnQgVGFpbENhbGxGYWN0b3JpYWwoaW50IG4sIGludCBhID0gMSkKewogICAgUHJpbnRTdGFja1RvcCgidGFpbCIpOwogICAgaWYobiA8IDIpCiAgICAgICAgcmV0dXJuIGE7CiAgICByZXR1cm4gVGFpbENhbGxGYWN0b3JpYWwobiAtIDEsIG4gKiBhKTsKfQoKaW50IE5vcm1hbENhbGxGYWN0b3JpYWwoaW50IG4pCnsKICAgIFByaW50U3RhY2tUb3AoIm5vcm1hbCIpOwogICAgaWYobiA8IDIpCiAgICAgICAgcmV0dXJuIDE7CiAgICByZXR1cm4gTm9ybWFsQ2FsbEZhY3RvcmlhbChuIC0gMSkgKiBuOwp9CgoKaW50IG1haW4oaW50IGFyZ2MsIGNoYXIgKmFyZ3ZbXSkKewogICAgc3QgPSAwOwogICAgY291dCA8PCBUYWlsQ2FsbEZhY3RvcmlhbCg1KSA8PCBlbmRsOwogICAgc3QgPSAwOwogICAgY291dCA8PCBOb3JtYWxDYWxsRmFjdG9yaWFsKDUpIDw8IGVuZGw7CiAgICByZXR1cm4gMDsKfQo=
-
upload with new input
-
result: Success time: 0s memory: 2860 kB returned value: 0
In tail call version, the stack top is: 0 In tail call version, the stack top is: 48 In tail call version, the stack top is: 96 In tail call version, the stack top is: 144 In tail call version, the stack top is: 192 120 In normal call version, the stack top is: 0 In normal call version, the stack top is: 48 In normal call version, the stack top is: 96 In normal call version, the stack top is: 144 In normal call version, the stack top is: 192 120


