Functions and Recursion in C

Modular C function examples showing parameter inputs and return values.
Modular C function examples showing parameter inputs and return values.

Functions divide C programs into reusable, modular procedures. Learn function prototypes, call by value vs call by reference, stack activation frames, and recursion.

Functions modularize C programs into reusable, isolated blocks of execution. They accept inputs via parameter lists and return values back to the calling scope.

A function prototype must precede function calls to inform the compiler of parameter types and return types before the body is compiled. This enables compile-time type validation across separate source files.

By default, C passes arguments by value, meaning the function works with local copies. To modify the caller's variables, pointers must be passed to simulate call-by-reference.

Interactive Runnable C Implementation

#include <stdio.h>
#include <stdlib.h>

// Function prototypes
unsigned long long factorial(unsigned int n);
void swap(int *a, int *b);
int add(int x, int y);

int main(void) {
    int a = 15, b = 30;
    printf("1. Sum function: %d + %d = %d\n", a, b, add(a, b));

    printf("\n2. Pass-by-Reference Swap:\n");
    printf("   Before swap: a = %d, b = %d\n", a, b);
    swap(&a, &b);
    printf("   After swap:  a = %d, b = %d\n", a, b);

    printf("\n3. Recursive Factorials:\n");
    for (unsigned int i = 0; i <= 6; i++) {
        printf("   %u! = %llu\n", i, factorial(i));
    }

    return EXIT_SUCCESS;
}

int add(int x, int y) {
    return x + y;
}

void swap(int *a, int *b) {
    int temp = *a;
    *a = *b;
    *b = temp;
}

// Recursive factorial with base case
unsigned long long factorial(unsigned int n) {
    if (n <= 1) {
        return 1; // Base case
    }
    return (unsigned long long)n * factorial(n - 1); // Recursive step
}

Open example in compiler

Expected Output

1. Sum function: 15 + 30 = 45

2. Pass-by-Reference Swap:
   Before swap: a = 15, b = 30
   After swap:  a = 30, b = 15

3. Recursive Factorials:
   0! = 1
   1! = 1
   2! = 2
   3! = 6
   4! = 24
   5! = 120
   6! = 720

Frequently Asked Questions

What causes a stack overflow in recursive C functions?

Each function call creates a new stack frame holding local variables and return addresses. Deep recursion without a terminating base case exhausts stack memory, triggering a segmentation fault.

Related examples