CodeMIRAI
0 XP

Functions

2 min read 5 runnable examples Quiz included

A function packages code under a name. In C, a function definition states its return type, name and parameters (each with a type).

C
#include <stdio.h>

int square(int x) {
    return x * x;
}

int main() {
    printf("%d\n", square(7));
    printf("%d\n", square(3) + square(4));
    return 0;
}

void functions

A function that returns nothing has the return type void:

C
#include <stdio.h>

void print_line(int length) {
    for (int i = 0; i < length; i++) {
        printf("-");
    }
    printf("\n");
}

int main() {
    print_line(20);
    printf("  Report\n");
    print_line(20);
    return 0;
}

Prototypes

C reads top to bottom, so a function must be declared before it's used. A prototype declares it early, and the full definition can come later:

C
#include <stdio.h>

double average(int a, int b);    // prototype

int main() {
    printf("%.1f\n", average(7, 8));
    return 0;
}

double average(int a, int b) {   // definition
    return (a + b) / 2.0;
}

Programs usually list prototypes at the top (or in a header file) so functions can be defined in any order.

Passed by value

C passes a copy of each argument, so a function can't change the caller's variables:

C
#include <stdio.h>

void try_to_double(int n) {
    n = n * 2;
    printf("inside: %d\n", n);
}

int main() {
    int x = 5;
    try_to_double(x);
    printf("outside: %d\n", x);
    return 0;
}

To let a function change a variable, you pass its address, which is exactly what scanf does with &. That's the topic of the pointers lesson.

Recursion

A function can call itself:

C
#include <stdio.h>

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

int main() {
    for (int i = 1; i <= 6; i++) {
        printf("%d! = %d\n", i, factorial(i));
    }
    return 0;
}
Finished this lesson?Mark it complete to earn +20 XP and move your progress on.