I have two code snippets that involve recursive manipulation of std::strings.
code snippet 1
#include <iostream>
#include <string>
void print_stuff(int min_n, int max_n)
{
struct local
{
static void build_stuff(
int min_n, int max_n, int cur_n,
int cur_c, int max_c, bool inc,
std::string & ret)
{
if (cur_c == max_c)
{
if (cur_n == min_n && !inc) return;
ret += '\n';
if (cur_n == max_n) inc = false;
int new_n = inc ? cur_n + 1 : cur_n - 1;
return build_stuff(
min_n, max_n, new_n,
0, new_n, inc, ret);
}
ret += '0' + cur_n;
return build_stuff(
min_n, max_n, cur_n,
cur_c + 1, max_c, inc, ret);
}
};
std::string stuff;
local::build_stuff(
min_n, max_n, min_n,
0, min_n, true, stuff);
std::cout << stuff;
}
int main()
{
print_stuff(1,9);
return 0;
}
code snippet 2
#include <iostream>
#include <string>
void insert_comma(const std::string & integer, std::string & result)
{
struct local
{
static void insert_comma_helper(const std::string & integer,
std::string & result)
{
int size = integer.size();
if (size < 4) { result = integer + ',' + result; return; }
return insert_comma_helper(
integer.substr(0, size - 3),
result = integer.substr(size - 3, 3) + ',' + result);
}
};
int size = integer.size();
if (size < 4) { result = integer; return; }
return local::insert_comma_helper(
integer.substr(0, size - 3),
result = integer.substr(size - 3, 3));
}
int main()
{
std::string integer;
std::string result;
while (true)
{
getline(std::cin,integer);
if (integer == "") break;
insert_comma(integer, result);
std::cout << result << std::endl;
}
return 0;
}
When I compile with -O3, g++ performs tail call optimization on the former, but not on the latter.
Why does this happen? Is there anything I can do to get tail call optimization on the second one?