summaryrefslogtreecommitdiff
path: root/fib.c
diff options
context:
space:
mode:
authorMartin Ashby <martin@ashbysoft.com>2022-11-16 19:17:08 +0000
committerMartin Ashby <martin@ashbysoft.com>2022-11-16 19:17:08 +0000
commitdb6e9bac370093b13cfb6f0b81ac066fed64b004 (patch)
tree5eed83a8b326236d3dc132ca66903c3fb97c8a73 /fib.c
parentbdc08b4f0507bc826c14737361f550ae0fc6b4c5 (diff)
downloadlearn-c-db6e9bac370093b13cfb6f0b81ac066fed64b004.tar.gz
learn-c-db6e9bac370093b13cfb6f0b81ac066fed64b004.tar.bz2
learn-c-db6e9bac370093b13cfb6f0b81ac066fed64b004.tar.xz
learn-c-db6e9bac370093b13cfb6f0b81ac066fed64b004.zip
Messing around replacing loops with recursion leveraging __attribute__((musttail)) in order to avoid stack overflow
Diffstat (limited to 'fib.c')
-rw-r--r--fib.c35
1 files changed, 35 insertions, 0 deletions
diff --git a/fib.c b/fib.c
new file mode 100644
index 0000000..6f510c2
--- /dev/null
+++ b/fib.c
@@ -0,0 +1,35 @@
+#include <stdio.h>
+
+static long fib_internal(int n, long a, long b) {
+ if (n == 0) {
+ return a;
+ } else if (n == 1) {
+ return b;
+ } else {
+ __attribute__((musttail))
+ return fib_internal(n-1, b, a + b);
+ }
+}
+
+long fib(int n) {
+ return fib_internal(n, 0, 1);
+}
+
+void test(int n) {
+ printf("fib [%d] = [%ld]\n", n, fib(n));
+}
+
+// static long recursion_depth(long n, long max) {
+// if (n >= max) {
+// return n;
+// }
+// __attribute__((musttail))
+// return recursion_depth(n+1, max);
+// }
+
+int main(void) {
+ for (int i=1; i<300; i++) {
+ test(i);
+ }
+ //printf("%ld\n", recursion_depth(0, 1000000000));
+} \ No newline at end of file