Functions in Functions!

For an argument, functions in the C language can take literal values, equations, the result from another function, or any combination of these items. It’s a feature that’s both flexible and confusing.

As an example, consider these three printf() functions:

printf("The result is %d\n",27);

printf("The result is %d\n",13+alpha);

printf("The result is %d\n",blorf());

The first statement uses a literal value. The second uses an equation, 13+alpha, and the final uses the return value of the function blorf(), which you can assume generates an integer.

It’s also possible to put the same function inside itself, as the following code demonstrates:

#include <stdio.h>

int twice(int v);

int main()
{
    int x;

    x = twice(twice(2));
    printf("The result is %d\n",x);

    return(0);
}

int twice(int v)
{
    return(v*2);
}

At Line 9, the twice() function uses the result of the twice() function to calculate its value.

Don’t freak out: No quantum particles were entangled to perform this type of operation. As with the sample printf() statements earlier, you simply need to work from inside the parentheses outward:

x = twice(twice(2));

The first operation is twice(2), which simply doubles the value 2. The result 4 is returned.

The result 4 is again passed to the twice() function, and the result 8 is returned.

Here’s the output:

The result is 8

You could even get really carried away and do something like this for Line 9:

x = twice(twice(twice(twice(2))));

That all still works, providing you properly match up the parentheses.

What you need to be careful of, however, is when you use a function within that same function. For example:

int twice(int v)
{
    return(twice(v*2));
}

In the return statement, the function twice() calls itself again. This is a perfectly legal maneuver in the C language. It’s called recursion.

re-kur-shn

The problem with the above example is that it’s a recursion without exit, so the function twice() would keep calling itself, doubling the value of v, until a nasty condition called a stack overflow occurs. That’s something you want to avoid.

You can craft a function to be recursive. You’ll find many advantages to doing so, although be aware that it’s a tricky and advanced programming concept. I’ll gingerly explore the operation in next week’s Lesson.