ccompiler.inOnline C Compiler & Docs
C Tutorial2026-03-152 min read

Learn how to write modular C functions. Master function prototypes, pass-by-value vs pass-by-reference, recursion, and stack frame memory.

What is a Function in C?

A function is a self-contained block of code that performs a specific task. Functions allow programmers to divide large software systems into reusable, maintainable, and testable modular subroutines.

In C, standard library functions such as printf(), scanf(), and strlen() are declared in header files, but you can define custom user-created functions to structure your logic.

Function Syntax & Declarations

A standard C function definition includes:

  1. Return Type: The data type returned to the caller (int, void, double, etc.).
  2. Function Name: A descriptive identifier.
  3. Parameter List: Input variables enclosed in parentheses.
  4. Body: Code statements enclosed in {} curly braces.
c (ISO Standard)
#include <stdio.h>

/* Function Prototype */
int addNumbers(int a, int b);

int main() {
    int x = 12;
    int y = 25;
    int sum = addNumbers(x, y);

    printf("The sum of %d and %d is %d\n", x, y, sum);
    return 0;
}

/* Function Definition */
int addNumbers(int a, int b) {
    return a + b;
}

Pass-by-Value vs. Pass-by-Reference

1. Pass-by-Value (Default)

In standard C, variables passed to functions are copied by value. Modifications made inside the function do not affect the caller's original variable:

c (ISO Standard)
#include <stdio.h>

void modifyValue(int num) {
    num = 100;
}

int main() {
    int original = 20;
    modifyValue(original);
    printf("Original after pass-by-value: %d\n", original); /* Still 20 */
    return 0;
}

2. Pass-by-Reference (Using Pointers)

To allow a function to modify variables in the caller's stack frame, pass the memory address of the variable using pointers:

c (ISO Standard)
#include <stdio.h>

void modifyByPointer(int *ptr) {
    *ptr = 100;
}

int main() {
    int original = 20;
    modifyByPointer(&original);
    printf("Original after pointer mutation: %d\n", original); /* Now 100 */
    return 0;
}

Recursive Functions in C

A recursive function calls itself to solve smaller sub-problems until reaching a base condition:

c (ISO Standard)
#include <stdio.h>

int factorial(int n) {
    if (n <= 1) {
        return 1;
    }
    return n * factorial(n - 1);
}

int main() {
    int n = 5;
    printf("Factorial of %d is %d\n", n, factorial(n));
    return 0;
}

Related Tutorials & Examples