<p>It seems to me that it would work perfectly well to do tail-recursion optimization in both C and C++, yet while debugging I never seem to see a frame stack that indicates this optimization. That is kind of good, because the stack tells me how deep the recursion is. However, the optimization would be kind of nice as well.</p>

<p>Do any C++ compilers do this optimization? Why? Why not?</p>

<p>How do I go about telling the compiler to do it?</p>

<ul>
<li>For MSVC: <code>/O2</code> or <code>/Ox</code></li>
<li>For GCC: <code>-O2</code> or <code>-O3</code></li>
</ul>

<p>How about checking if the compiler has done this in a certain case?</p>

<ul>
<li>For MSVC, enable PDB output to be able to trace the code, then inspect the code</li>
<li>For GCC..?</li>
</ul>

<p>I'd still take suggestions for how to determine if a certain function is optimized like this by the compiler (even though I find it reassuring that Konrad tells me to assume it)</p>

<p>It is always possible to check if the compiler does this at all by making an infinite recursion and checking if it results in an infinite loop or a stack overflow (I did this with GCC and found out that <code>-O2</code> is sufficient), but I want to be able to check a certain function that I know will terminate anyway. I'd love to have an easy way of checking this :)</p>

<hr>

<p>After some testing, I discovered that destructors ruin the possibility of making this optimization. It can sometimes be worth it to change the scoping of certain variables and temporaries to make sure they go out of scope before the return-statement starts.</p>

<p>If any destructor needs to be run after the tail-call, the tail-call optimization can not be done.</p>

[{'answer_id': 34129, 'author': 'Konrad Rudolph', 'author_id': 1968, 'author_profile': 'https://Stackoverflow.com/users/1968', 'pm_score': 8, 'selected': True, 'text': '<p><strong>All current mainstream compilers perform tail call optimisation</strong> fairly well (and have done for more than a decade), <a href="https://godbolt.org/g/TjqTHV" rel="noreferrer">even for mutually recursive calls</a> such as:</p>\n\n<pre><code>int bar(int, int);\n\nint foo(int n, int acc) {\n    return (n == 0) ? acc : bar(n - 1, acc + 2);\n}\n\nint bar(int n, int acc) {\n    return (n == 0) ? acc : foo(n - 1, acc + 1);\n}\n</code></pre>\n\n<p>Letting the compiler do the optimisation is straightforward: Just switch on optimisation for speed:</p>\n\n<ul>\n<li>For MSVC, use <code>/O2</code> or <code>/Ox</code>.</li>\n<li>For GCC, Clang and ICC, use <code>-O3</code></li>\n</ul>\n\n<p>An easy way to check if the compiler did the optimisation is to perform a call that would otherwise result in a stack overflow — or looking at the assembly output.</p>\n\n<p>As an interesting historical note, tail call optimisation for C was added to the GCC in the course of a <a href="http://www.complang.tuwien.ac.at/schani/diplarb.ps" rel="noreferrer">diploma thesis</a> by Mark Probst. The thesis describes some interesting caveats in the implementation. It\'s worth reading.</p>\n'}, {'answer_id': 34139, 'author': 'Greg Whitfield', 'author_id': 2102, 'author_profile': 'https://Stackoverflow.com/users/2102', 'pm_score': 4, 'selected': False, 'text': '<p>Most compilers don\'t do any kind of optimisation in a debug build.</p>\n\n<p>If using VC, try a release build with PDB info turned on - this will let you trace through the optimised app and you should hopefully see what you want then. Note, however, that debugging and tracing an optimised build will jump you around all over the place, and often you cannot inspect variables directly as they only ever end up in registers or get optimised away entirely. It\'s an "interesting" experience...</p>\n'}, {'answer_id': 71115, 'author': '0124816', 'author_id': 11521, 'author_profile': 'https://Stackoverflow.com/users/11521', 'pm_score': 3, 'selected': False, 'text': "<p>As Greg mentions, compilers won't do it in debug mode. It's ok for debug builds to be slower than a prod build, but they shouldn't crash more often: and if you depend on a tail call optimization, they may do exactly that. Because of this it is often best to rewrite the tail call as an normal loop. :-(</p>\n"}, {'answer_id': 220660, 'author': 'Tom Barta', 'author_id': 29839, 'author_profile': 'https://Stackoverflow.com/users/29839', 'pm_score': 5, 'selected': False, 'text': '<p>gcc 4.3.2 completely inlines this function (crappy/trivial <code>atoi()</code> implementation) into <code>main()</code>.  Optimization level is <code>-O1</code>.  I notice if I play around with it (even changing it from <code>static</code> to <code>extern</code>, the tail recursion goes away pretty fast, so I wouldn\'t depend on it for program correctness.</p>\n\n<pre><code>#include &lt;stdio.h&gt;\nstatic int atoi(const char *str, int n)\n{\n    if (str == 0 || *str == 0)\n        return n;\n    return atoi(str+1, n*10 + *str-\'0\');\n}\nint main(int argc, char **argv)\n{\n    for (int i = 1; i != argc; ++i)\n        printf("%s -&gt; %d\\n", argv[i], atoi(argv[i], 0));\n    return 0;\n}\n</code></pre>\n'}, {'answer_id': 35649259, 'author': 'Martin Bonner supports Monica', 'author_id': 771073, 'author_profile': 'https://Stackoverflow.com/users/771073', 'pm_score': 5, 'selected': False, 'text': "<p>As well as the obvious (compilers don't do this sort of optimization unless you ask for it), there is a complexity about tail-call optimization in C++:  destructors.</p>\n\n<p>Given something like:</p>\n\n<pre><code>   int fn(int j, int i)\n   {\n      if (i &lt;= 0) return j;\n      Funky cls(j,i);\n      return fn(j, i-1);\n   }\n</code></pre>\n\n<p>The compiler can't (in general) tail-call optimize this because it needs\nto call the destructor of <code>cls</code> <em>after</em> the recursive call returns.</p>\n\n<p>Sometimes the compiler can see that the destructor has no externally visible side effects (so it can be done early), but often it can't.</p>\n\n<p>A particularly common form of this is where <code>Funky</code> is actually a <code>std::vector</code> or similar.</p>\n"}]
['https://Stackoverflow.com/questions/34125', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2971/']