Aah, recursion, the favorite pet of every programmer. Surely it must be possible to recurse even in Windows batch files (I'm still trying to prove Turing-completeness, by the way :-)).
The first tentative test would be an infinite recursion:
And know what? It works. Well, kinda:
But that's ok, we didn't expect this to do anything useful except of causing a stack overflow. But as we can see, cmd has a stack of some sort and seemingly manages it well enough to allow for recursion.
Time for another test, this time something remotely practical: Factorials. Never mind that those are more easily done with iteration, we want to make sure that recursion works properly:
We need a temporary variable at the end, unfortunately, since cmd does not
allow computations inline. But aside from that it looks pretty much how it
should. The case for breaking the recursion is also provided in the form of an
IF block (sorry, no functional programming
niceties, like different function definitions).
But does it work? Oh, sure it does:
And my calculator tells me that those are actually correct. 12! is unfortunately the highest factorial we can compute with it, since we are limited to 32-bit signed integers. A minor bug is still present when using negative numbers, though (infinite recursion, again). This is corrected in the attached version (as well as giving a helpful hint when running the batch without arguments).
Just as a side note, a fun way to implement factorial calculation by leveraging cmd's own „calculator“:
We simply construct the complete term and evaluate that by using SET /A. Nothing fancy, but probably faster than
the recursion.
| Anhang | Größe |
|---|---|
| Infinite recursion test | 28 Bytes |
| Recursive factorial calculation | 486 Bytes |
| Non-recursive factorial calculation | 163 Bytes |