C Functions

A function has a declaration (prototype), a definition and calls.

Call by Value vs Call by Reference

C
#include <stdio.h>

void swapVal(int a, int b) { int t = a; a = b; b = t; }      // copies
void swapRef(int *a, int *b) { int t = *a; *a = *b; *b = t; } // addresses

int main() {
    int x = 10, y = 20;
    swapVal(x, y);
    printf("After swapVal: x=%d y=%d\n", x, y);
    swapRef(&x, &y);
    printf("After swapRef: x=%d y=%d\n", x, y);
    return 0;
}
After swapVal: x=10 y=20 After swapRef: x=20 y=10

Recursion

C
#include <stdio.h>
long fact(int n) { return n <= 1 ? 1 : n * fact(n - 1); }
int gcd(int a, int b) { return b == 0 ? a : gcd(b, a % b); }

int main() {
    printf("5! = %ld\n", fact(5));
    printf("gcd(48, 18) = %d\n", gcd(48, 18));
    return 0;
}
5! = 120 gcd(48, 18) = 6

Storage Classes

ClassScopeLifetimeDefault
autoBlockBlockGarbage
registerBlockBlockGarbage
staticBlock/fileWhole program0
externGlobalWhole program0
Track your progress through the C course