0

Here is a simple recursive function that emulates a while loop. In function, I return value in the end step but in the backward step of recursion I don't return value... Function surprisingly does not return NULL value but instead returns the value as it supposed to. Can someone please explain why C permits this?

#include <stdio.h>

int while_recursion(int c) {
    c++;
    if (c < 10) {
        while_recursion(c);  // <---------- NOTICE THAT I DON"T RETURN VALUE IN BACKWARD PASS
    } else
        return c;
}

int main() {
    printf("%i\n", while_recursion(0));
    return 0;
}
  • 2
    It's part of the language definition. You can shoot your foot off if you want. But a good compiler will warn you: `warning: non-void function does not return a value in all control paths [-Wreturn-type]`. – Jeff Holt Aug 27 '21 at 20:04
  • 3
    That's *undefined behavior* and it just happens to "work" correctly (presumably because the return value from `return c;` is written into the EAX/RAX register and not overwritten anywhere) – UnholySheep Aug 27 '21 at 20:05
  • You missed an opportunity to avoid variable mutation, which is part of the point of using recursion instead of iteration: `if (c < 9) { return while_recursion(c + 1); }` Now that is almost purely functional. – Kaz Aug 27 '21 at 20:06
  • 1
    In one line: `int while_rec(int c) { return (c < 9) ? while_rec(c + 1) : c; }` – Kaz Aug 27 '21 at 20:07
  • *"why C permits this?"* Because C permits anything that compiles. C doesn't make any attempt to force you to follow the rules. It's up to you to read the rules, understand the rules, and follow the rules. If you choose to ignore the rules, your code is garbage, and it's nobody's fault but your own. – user3386109 Aug 27 '21 at 20:12
  • 3
    ObSillyAnalogy: "I was working on the brakes on the front wheels of my car. When I put the wheels back on, I forgot to fasten the lugnuts. Then, when I went to test the car, I drove down the highway at 60mph. With the front wheels not fastened on. And they didn't fall off. Why didn't they fall off? Why did it work? Why didn't I have a horrible crash?" – Steve Summit Aug 27 '21 at 20:18

0 Answers0