Recursive macros

Macros may call themselves recursively (as long as they terminate). The following example shows how we can use a macro to calculate factorial at compile time. This example makes use of strong typing on both the argument and return type.

Before translationAfter translation
@def int factorial(int n) =
{
    @if (n <= 1) {1}
    @else        {n*factorial(n-1)}
}
int f()
{
    return factorial(5);
}






int f()
{
    return 120;
}

Now consider that the return type on the factorial macro isn’t specified:

Before translationAfter translation
@def factorial(int n) =
{
    @if (n <= 1) {1}
    @else        {n*factorial(n-1)}
}
int f()
{
    return factorial(5);
}






int f()
{
    return 5*4*3*2*1;
}

If we don’t strongly type the argument then we end up with an erroneous definition because of lack of bracketing:

Before translationAfter translation
@def factorial(n) =
{
    @if (n <= 1) {1}
    @else        {n*factorial(n-1)}
}
int f()
{
    // oops!
    return factorial(5);
}






int f()
{
    // oops!
    return 5*5-1*5-1-1*5-1-1-1*1;
}