Find limit of recursion: Difference between revisions

Content added Content deleted
(Add ZIg example with showcase of force-enabling and force-disabling tail-recursion elimination, thus making behaviour consistent in all optimization modes.)
m (→‎{{header|Zig}}: Add third example where compiler automatically decides to do (or not to do) STRE (like it works with many other languages here))
Line 3,390: Line 3,390:
=={{header|Zig}}==
=={{header|Zig}}==
{{Trans|C}}
{{Trans|C}}

===Leave TRE to the compiler===
'''Works with:''' 0.11.x, 0.12.0-dev.1381+61861ef39
In this version, Zig compiler is free to (not) optimize recursive function, so behaviour may change from one optimization mode to another, like it was with 2-nd example from C section.
<syntaxhighlight lang="zig">const std = @import("std");

fn recurse(i: c_uint) void {
std.debug.print("{d}\n", .{i});
// We use wrapping addition operator here to mirror C behaviour.
recurse(i +% 1);
// Line above is equivalent to:
// @call(.auto, recurse, .{i +% 1});
}

pub fn main() void {
recurse(0);
return;
}</syntaxhighlight>


===Force-disable TRE===
===Force-disable TRE===
Line 3,410: Line 3,428:
Segmentation fault occurs at different values of "i", depending on running platform, but on my platform (with stack size reported by ulimit as 16384) both C and Zig versions (compiled without optimizations output last value in approximately [523500, 524000] range.
Segmentation fault occurs at different values of "i", depending on running platform, but on my platform (with stack size reported by ulimit as 16384) both C and Zig versions (compiled without optimizations output last value in approximately [523500, 524000] range.


gcc compiler with -O2 flag eliminated tail recursion, as mentioned in second example from C section, but in this Zig example recurse function is never turned into loop, even when enabling different optimization modes — we explicitly prohibited compiler from doing it in any optimize/build mode!
gcc compiler with -O2 flag eliminated tail recursion, as mentioned in 2-nd example from C section, but in this Zig example recurse function is never turned into loop, even when enabling different optimization modes — we explicitly prohibited compiler from doing it in any optimize/build mode!


===Force-enable TRE===
===Force-enable TRE===