Core Concepts

Functions

Write reusable C functions with parameters, return values, and function prototypes.

C Functions

Functions must be declared before use. A function prototype (declaration) tells the compiler the function's signature before the full definition.

Pass by Value

In C, arguments are passed by value — the function gets a copy. Changes to parameters don't affect the original variables.

Pass by Pointer (Pass by Reference)

To modify a variable from a function, pass its address (pointer) instead.

Recursive Functions

Functions can call themselves. Always need a base case to stop recursion.

Example

c
#include <stdio.h>

/* Function prototypes (declarations) */
int add(int a, int b);
double power(double base, int exp);
void swap(int *a, int *b);
int factorial(int n);

int main() {
    printf("%d\n", add(5, 3));          /* 8 */
    printf("%.2f\n", power(2.0, 10));   /* 1024.00 */

    int x = 10, y = 20;
    printf("Before: %d %d\n", x, y);
    swap(&x, &y);
    printf("After: %d %d\n", x, y);

    printf("5! = %d\n", factorial(5));  /* 120 */

    return 0;
}

/* Function definitions */
int add(int a, int b) {
    return a + b;
}

double power(double base, int exp) {
    double result = 1.0;
    for (int i = 0; i < exp; i++) {
        result *= base;
    }
    return result;
}

/* Pass by pointer - modifies original variables */
void swap(int *a, int *b) {
    int temp = *a;
    *a = *b;
    *b = temp;
}

/* Recursive function */
int factorial(int n) {
    if (n <= 1) return 1;          /* base case */
    return n * factorial(n - 1);   /* recursive case */
}
Try it yourself — C