Codiqo

Learn C · lesson 22 of 60 · about 8 minutes

Parameters and Return Values

Work out how full the disk is now and after the next backup: pass values into a function with parameters and send the result back with return.

What you'll learn

  • Declare parameters
  • Return a value
  • Use a returned value in expressions

Full now, and after the next backup

The summary should say how full the disk is now, and how full it would be after one more backup of the same size. That's the same sum twice with different numbers: kib * 100 / DISK_KIB. A function int percent_full(int kib) takes the number of KiB as a parameter and hands the percentage back with return, so main can print it.

Inputs and an output

int area(int w, int h) takes two int parameters and returns an int. Inside, return w * h; sends the result back to whoever called it, and ends the function.

When you call area(3, 4), the arguments 3 and 4 are copied into w and h.

A function that returns

#include <stdio.h>

int area(int w, int h) {
    return w * h;
}

int main(void) {
    int room = area(4, 3);
    printf("%d\n", room);
    printf("%d\n", area(2, 2) + area(1, 5));
    return 0;
}

Output

12
9

Step through a call: into the function and back

#include <stdio.h>

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

int main(void) {
    int a = square(3);
    printf("%d\n", a + 1);
    return 0;
}

Output

10

Returning early

#include <stdio.h>

const char *sign(int n) {
    if (n < 0) return "negative";
    if (n == 0) return "zero";
    return "positive";
}

int main(void) {
    printf("%s %s %s\n", sign(-2), sign(0), sign(9));
    return 0;
}

Output

negative zero positive

Tip

const char * is the type for a piece of fixed text. You'll learn what the * means in the Pointers unit.

Now try it yourself

This lesson is free in Codiqo, with 9 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.