SyntaxPilot
Courses/C Programming/Lesson 7
Video coming soonThis lesson’s video is being made

Start with the notes below; the video appears here as soon as it is on YouTube.

C Programming · Lesson 7 of 30

Functions

queued

These are the notes for C episode 7. Until now everything lived inside main, and the same formula got copy-pasted wherever it was needed. Here you build your own named "machines": write a rule once, give it a name, and call it anywhere. You will learn how to define and call a function, parameters and arguments, return, void functions, prototypes (and the "implicit declaration" error), what happens when you forget return, pass by value, local variables and scope, and argument-count errors. Every example below was compiled with gcc -O2 -Wno-unused-result main.c -o main -lm (gcc 13, the same command as the SyntaxPilot compiler) and run as shown.

The problem: the GST formula, three times

Bhaiya's chai stall has registered for GST: 5% on every item. The obvious way is to write the formula once and copy it for each item:

#include <stdio.h>

int main() {
    float chai = 15, samosa = 20, lassi = 40;
    printf("Chai:   %.2f\n", chai + chai * 5 / 100);
    printf("Samosa: %.2f\n", samosa + samosa * 5 / 100);
    printf("Lassi:  %.2f\n", lassi + lassi * 5 / 100);
    return 0;
}

Output:

Chai:   15.75
Samosa: 21.00
Lassi:  42.00

Then the rate goes up to 12%. We fix chai and samosa, the phone rings, and we forget lassi:

    printf("Chai:   %.2f\n", chai + chai * 12 / 100);
    printf("Samosa: %.2f\n", samosa + samosa * 12 / 100);
    printf("Lassi:  %.2f\n", lassi + lassi * 5 / 100);

Output:

Chai:   16.80
Samosa: 22.40
Lassi:  42.00

No error, no warning, and every lassi customer gets a wrong bill.

Why? One rule ("add GST") lived in three places. Every change means finding and fixing every copy, and sooner or later you miss one. We want the rule written once, with a name, so we can say "with GST of this price".

The fix: a function

Think of a sugarcane juice machine:

Juice stall C
The machine is built once the function definition, written once
You feed in sugarcane the parameter: what goes in (float price)
Juice comes out the return value: what comes out (return ...;)
"One glass, please" a call: with_gst(15); 15 is the argument
#include <stdio.h>

float with_gst(float price) {
    return price + price * 5 / 100;
}

int main() {
    printf("Chai:   %.2f\n", with_gst(15));
    printf("Samosa: %.2f\n", with_gst(20));
    printf("Lassi:  %.2f\n", with_gst(40));
    return 0;
}

Output:

Chai:   15.75
Samosa: 21.00
Lassi:  42.00

Each call jumps into the function, price takes the argument's value, return hands the answer back, and the call is replaced by that answer inside printf. Now the rate changes to 12% in one place:

float with_gst(float price) {
    return price + price * 12 / 100;
}

Output:

Chai:   16.80
Samosa: 22.40
Lassi:  44.80

Nothing left to miss.

Anatomy of a function

float with_gst(float price) {
//^     ^         ^
//|     |         parameter: type and name of what goes in
//|     name
//return type: the type of what comes out
    return price + price * 5 / 100;   // body: the rule, ending with return
}
  • A function can have several parameters separated by commas: int max(int a, int b).
  • main is a function too: the one C calls first when the program starts. Its return 0; tells the system "finished fine".
  • Parameter = the variable in the definition (price). Argument = the value you pass in the call (15).

void: a function that just does a job

A doorbell rings and gives you nothing back. A function that returns nothing has the return type void.

#include <stdio.h>

void line() {
    printf("--------------------\n");
}

int main() {
    line();
    printf("  SHARMA CHAI STALL\n");
    line();
    return 0;
}

Output:

--------------------
  SHARMA CHAI STALL
--------------------

Empty brackets: nothing goes in. void: nothing comes out. You still need the () when calling it: line();.

Calling a function too early: prototypes

The compiler reads your file from top to bottom, once. If main comes first and calls a function defined below it:

#include <stdio.h>

int main() {
    printf("Chai: %.2f\n", with_gst(15));
    return 0;
}

float with_gst(float price) {
    return price + price * 5 / 100;
}
main.c: In function 'main':
main.c:4:28: warning: implicit declaration of function 'with_gst' [-Wimplicit-function-declaration]
    4 |     printf("Chai: %.2f\n", with_gst(15));
      |                            ^~~~~~~~
main.c:4:22: warning: format '%f' expects argument of type 'double', but argument 2 has type 'int' [-Wformat=]
    4 |     printf("Chai: %.2f\n", with_gst(15));
      |                   ~~~^     ~~~~~~~~~~~~
      |                      |     |
      |                      |     int
      |                      double
      |                   %.2d
main.c: At top level:
main.c:8:7: error: conflicting types for 'with_gst'; have 'float(float)'
    8 | float with_gst(float price) {
      |       ^~~~~~~~
main.c:4:28: note: previous implicit declaration of 'with_gst' with type 'int()'
    4 |     printf("Chai: %.2f\n", with_gst(15));
      |                            ^~~~~~~~

C hadn't seen with_gst, so it guessed it returns int (an implicit declaration). When it reached the real function returning float, the guess conflicted.

The fix is a prototype (a function declaration): the function's first line with a semicolon, placed at the top, like a menu card that announces what's coming.

#include <stdio.h>

float with_gst(float price);

int main() {
    printf("Chai: %.2f\n", with_gst(15));
    return 0;
}

float with_gst(float price) {
    return price + price * 5 / 100;
}

Output:

Chai: 15.75

Forgetting return

#include <stdio.h>

int with_tip(int bill) {
    int total = bill + 10;
}

int main() {
    printf("Total: %d\n", with_tip(100));
    return 0;
}

Output:

Total: 0

Not 110, and no error or warning with the stage's command. The function promised an int but never returned one, so main got a garbage value (here 0; it could be anything on another compiler). Add return total;:

int with_tip(int bill) {
    int total = bill + 10;
    return total;
}

Output: Total: 110. (With gcc -Wall you'd see warning: control reaches end of non-void function.)

Pass by value: the function gets a photocopy

#include <stdio.h>

void add_tip(int bill) {
    bill = bill + 10;
    printf("Inside add_tip: %d\n", bill);
}

int main() {
    int bill = 100;
    add_tip(bill);
    printf("In main: %d\n", bill);
    return 0;
}

Output:

Inside add_tip: 110
In main: 100

Think of submitting a form at an office: you keep the original and the clerk gets a photocopy. Whatever he writes on the copy, your original is untouched, and the copy is thrown away at the end. In C, a parameter is a new variable holding a copy of the argument. This is pass by value. The two bills just share a name.

To get the new value back, return it and store it:

#include <stdio.h>

int add_tip(int bill) {
    return bill + 10;
}

int main() {
    int bill = 100;
    bill = add_tip(bill);
    printf("In main: %d\n", bill);
    return 0;
}

Output: In main: 110. Later in the course, pointers let a function change the original directly (that's what scanf does with &bill).

Scope: a function's own variables

The cook's rough notes stay in the kitchen; you only get what's served. A variable created inside a function is local: it exists only inside that function, and only while it runs.

#include <stdio.h>

void make_bill() {
    int total = 250;
}

int main() {
    make_bill();
    printf("Total: %d\n", total);
    return 0;
}
main.c: In function 'main':
main.c:9:27: error: 'total' undeclared (first use in this function)
    9 |     printf("Total: %d\n", total);
      |                           ^~~~~
main.c:9:27: note: each undeclared identifier is reported only once for each function it appears in

Where a name can be used is its scope. The only way a value leaves a function is return. (A variable declared outside every function is a global variable and is visible everywhere; useful sometimes, but it makes programs harder to follow, so prefer parameters and return values.)

The arguments must match

printf("Chai:   %.2f\n", with_gst());
main.c: In function 'main':
main.c:8:30: error: too few arguments to function 'with_gst'
    8 |     printf("Chai:   %.2f\n", with_gst());
      |                              ^~~~~~~~
main.c:3:7: note: declared here
    3 | float with_gst(float price) {
      |       ^~~~~~~~

And with_gst(15, 20) gives error: too many arguments to function 'with_gst'. One parameter means exactly one argument.

Common mistakes (and the real gcc messages)

Mistake Code What gcc says / what happens
Calling before the definition, no prototype with_gst(15) in main, function below warning: implicit declaration of function 'with_gst' then error: conflicting types for 'with_gst'
No return in a non-void function int with_tip(int b) { int t = b + 10; } no error; garbage value (Total: 0)
Expecting a function to change your variable void add_tip(int bill) { bill += 10; } no error; main's bill is unchanged
Using another function's local variable printf("%d", total); in main error: 'total' undeclared (first use in this function)
Too few / too many arguments with_gst(), with_gst(15, 20) error: too few arguments to function 'with_gst' / too many arguments
Forgetting () in a call line; no call happens (with -Wall: warning: statement with no effect)
Prototype without ; float with_gst(float price) at the top a cascade of syntax errors

Mini project: a bill calculator built from functions

#include <stdio.h>

float price_of(int item) {
    switch (item) {
        case 1: return 15;
        case 2: return 20;
        case 3: return 40;
        default: return 0;
    }
}

float with_gst(float amount) {
    return amount + amount * 5 / 100;
}

void line() { printf("------------------\n"); }

int main() {
    int item, qty;
    scanf("%d %d", &item, &qty);
    float subtotal = price_of(item) * qty;
    line();
    printf("Subtotal: %.2f\n", subtotal);
    printf("With GST: %.2f\n", with_gst(subtotal));
    line();
    return 0;
}

Input 2 6:

------------------
Subtotal: 120.00
With GST: 126.00
------------------
  • return also leaves the function, so no break is needed after return inside a switch.
  • main reads almost like English because every job has its own named function.

Practice

  1. Write int square(int n) and print the squares of 1 to 10.
  2. Write float area(float r) for a circle (3.14 × r × r).
  3. Write int max(int a, int b) using ? :.
  4. Write int is_even(int n) that returns 1 or 0, and use it in an if.
  5. Why does scanf need &bill but our with_gst doesn't need &price?
Solutions and hints

All four in one program (verified):

#include <stdio.h>

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

float area(float r) {
    return 3.14 * r * r;
}

int max(int a, int b) {
    return (a > b) ? a : b;
}

int is_even(int n) {
    return n % 2 == 0;
}

int main() {
    for (int i = 1; i <= 10; i++)
        printf("%d ", square(i));
    printf("\n");
    printf("Area: %.2f\n", area(2));
    printf("Max: %d\n", max(7, 12));
    int n = 9;
    if (is_even(n))
        printf("%d is even\n", n);
    else
        printf("%d is odd\n", n);
    return 0;
}

Output:

1 4 9 16 25 36 49 64 81 100 
Area: 12.56
Max: 12
9 is odd

is_even can return the comparison directly: n % 2 == 0 is already 1 or 0.

5. scanf must change your variable, so it needs its address; a plain argument would only give it a copy. with_gst only reads the price and returns a new value, so a copy is enough.

Quick quiz

What does this print?

void change(int x) {
    x = 50;
}

int main() {
    int x = 5;
    change(x);
    printf("%d", x);
}
  • A. 50
  • B. 5
  • C. 0
  • D. Error
Answer

B: 5. change gets a copy of x. Setting the copy to 50 doesn't touch main's x. Same name, two different variables.

Interview questions

  • What is the difference between a parameter and an argument?
  • What is a function prototype and why is it needed?
  • What does "implicit declaration of function" mean?
  • What is pass by value? How can a C function change a caller's variable?
  • What happens if a non-void function reaches its end without return?
  • What is the difference between a local and a global variable?
  • Can a function return more than one value? (Not directly; later: structs or pointers.)
  • Why is main a function, and what does its return value mean?

Glossary

Term Meaning Example
Function A named block of code you write once and call anywhere with_gst
Definition The full function: header and body float with_gst(float price) { ... }
Return type The type of the value the function gives back float
Parameter A variable in the definition that receives a value float price
Argument The value passed in a call 15 in with_gst(15)
Call Using a function by name with arguments with_gst(15)
return Hands a value back and leaves the function return price * 2;
Return value The value a call is replaced by 15.75
void "Nothing": no return value (or no parameters) void line()
Prototype (declaration) The function's header with ;, announcing it before use float with_gst(float price);
Implicit declaration C guessing an unknown function returns int (an error-prone old rule) the warning when calling too early
Garbage value Leftover junk you get when no value was set Total: 0 without return
Pass by value The parameter gets a copy of the argument add_tip can't change main's bill
Local variable A variable that exists only inside its function total in make_bill
Scope The part of the program where a name can be used 'total' undeclared in main
Global variable A variable declared outside every function, visible everywhere int count = 0; above main

Summary

  • A function lets you write a rule once and call it by name: type name(params) { ...; return value; }.
  • void functions do a job and return nothing.
  • If a function is defined after main, put a prototype at the top.
  • A non-void function must return a value, or you get garbage.
  • Arguments are passed by value: the function works on copies. Return the new value and store it.
  • Local variables live only inside their function; the number of arguments must match the parameters.

Next episode: arrays. Our loop added up the day's bills but forgot each one as soon as it was added. To keep every bill we'd need a hundred variables, so next time we invent arrays.