DEV Community

Aditya
Aditya

Posted on Originally published at techvaniai.blogspot.com

Functions in C: Declaration, Definition and Call by Value (C Learning Guide, Part 5)

In Part 5 of our beginner C series the packing tool's logic moves out of main and into functions: write the check once, give it a name, call it from ten places, fix it in one spot.

What the full guide covers:

  • Declaration vs definition vs call: what each one says, and which of them the compiler and linker actually need.
  • Parameters in, return value out: the input/output contract of a function, and why void appears on both sides of main(void).
  • Prototypes: how to call a function that is defined later in the file, and the compiler errors you get when you skip this.
  • Call by value: C hands every function a copy of its arguments, so a callee cannot silently change the caller's variables - shown with a failing swap attempt and the real compiler output for each wrong turn.
  • Tested programs with verified expected output, plus the classic beginner mistakes (missing return, implicit declaration, swapped parameter order) with the exact diagnostics gcc prints.

A taste of the style - one job, written once, called three times:

#include <stdio.h>
int boxesNeeded(int items, int capacity) {
    int boxes = items / capacity;
    if (items % capacity != 0) {
        boxes = boxes + 1;
    }
    return boxes;
}
int main(void) {
    printf("items=%d capacity=%d boxes=%d\n", 17, 6, boxesNeeded(17, 6));
    printf("items=%d capacity=%d boxes=%d\n", 12, 6, boxesNeeded(12, 6));
    printf("items=%d capacity=%d boxes=%d\n", 5, 6, boxesNeeded(5, 6));
    return 0;
}
Enter fullscreen mode Exit fullscreen mode

Output:

items=17 capacity=6 boxes=3
items=12 capacity=6 boxes=2
items=5 capacity=6 boxes=1
Enter fullscreen mode Exit fullscreen mode

Read the full guide with every example and practice exercise: Functions in C: Declaration, Definition and Call by Value - C Learning Guide, Part 5

New to the series? It starts from zero setup here: Programming in C - Learning Guide series index

Top comments (0)