Skip to content

Beginner · Functions and arrays · topic 11 of 60 · 25 min

Functions

Explanation

A function is a named block of code with parameters and a return type. Declare it before use with a prototype (int area(int w, int h);) and define it anywhere. C passes arguments by value: the function gets copies, so changing a parameter does not change the caller's variable (pointers, in module 5, change that). void means "returns nothing" or "takes nothing".

Why functions?

Splitting a program into functions gives each job a name (calculate_gst, print_receipt), lets you reuse code, and lets you test pieces separately. Large C programs like the Linux kernel are millions of lines of small functions.

c
#include <stdio.h>

double with_gst(double amount, double rate);   /* prototype (declaration) */
void print_line(int width);

int main(void) {
    double total = with_gst(1000.0, 18.0);
    print_line(20);
    printf("Total: %.2f\n", total);            /* Total: 1180.00 */
    print_line(20);
    return 0;
}

double with_gst(double amount, double rate) {  /* definition */
    return amount + amount * rate / 100.0;
}

void print_line(int width) {                    /* void: returns nothing */
    for (int i = 0; i < width; i++) putchar('-');
    putchar('\n');
}

Prototypes

The compiler reads a file from top to bottom. A prototype tells it the function's name, return type and parameter types before the call appears, so it can check the call. In old C, calling an undeclared function was allowed and the compiler guessed int; since C99 that is not allowed, and modern GCC (14 and later) reports it as an error ("implicit declaration of function"). Put prototypes at the top of the file or in a header (module 8).

Pass by value

c
void try_to_double(int n) {
    n = n * 2;                 /* changes only the local copy */
}

int main(void) {
    int x = 10;
    try_to_double(x);
    printf("%d\n", x);         /* still 10 */
    return 0;
}
To let a function change the caller's variable, pass its address (a pointer, module 5), or return the new value.

A function can return only one value. Return the main result, and use pointers (module 5) or a struct (module 7) when you need several.

void and empty parameter lists

Write int main(void) and void print_menu(void) for functions with no parameters. In C before C23, an empty list int f() meant "unknown parameters", which disables checking; in C23 () finally means no parameters too, but (void) is clear in every version.

Careful: Forgetting to return a value from a non-void function (for example on one branch of an if) is undefined behaviour when the caller uses the result; gcc -Wall warns "control reaches end of non-void function". Also make sure the prototype and definition match exactly; mismatches cause wrong values, not always errors.

A function is a contract

Document what each function expects and promises: "is_valid_pin(code) returns 1 if code is a 6-digit number not starting with 0". Small functions with one job and a clear contract are the easiest to test and reuse.

Think of it like this: A function is like a counter at a post office: you hand over copies of your documents (pass by value), the clerk does one job and hands back one receipt (the return value). Your original documents at home are never touched.
Tip: Keep functions short (fits on one screen) and name them with verbs in snake_case, the common C style: read_marks, print_report, find_max.

Need help?

Stuck on a word or an idea? Search this course, or every course, and jump straight to the explanation or a worked question.

Try:

Watch the lesson

Functions · 1/6

Functions

In this lesson you will write your own C functions.

Prefer a video by a teacher? Find free videos on “c functions prototype pass by value return tutorial” on YouTube ↗

In real life: A loan calculator split into functions

A cooperative bank's simple loan program has separate functions for the monthly rate, the EMI formula and printing a summary line. Each is tested on its own, and main just connects them.

c
#include <stdio.h>
#include <math.h>

double monthly_rate(double annual_percent) { return annual_percent / 12.0 / 100.0; }

double emi(double principal, double annual_percent, int months) {
    double r = monthly_rate(annual_percent);
    if (r == 0) return principal / months;
    double f = pow(1 + r, months);
    return principal * r * f / (f - 1);
}

int main(void) {
    printf("EMI: %.2f\n", emi(500000, 9.0, 60));   /* about 10379.18; compile with -lm */
    return 0;
}

Practice (0/3 done)

Task 1 · Question

What does this print? int add_one(int n) { n = n + 1; return n; } … int a = 5; int b = add_one(a); printf("%d %d\n", a, b);

Task 2 · Question

Which line causes "implicit declaration of function" on a modern compiler? 1: #include <stdio.h> 2: int main(void) { 3: printf("%d\n", square(4)); 4: return 0; 5: } 6: int square(int n) { return n * n; }

Task 3 · Practice

Write a program with three functions: int max3(int a, int b, int c), double average(int a, int b, int c) and void print_report(const char *name, int a, int b, int c) that uses the other two. Put prototypes at the top and call print_report from main for two students.

Quick quiz

Question 1

1.How does C pass a plain int argument to a function?

Question 2

2.What is a prototype for?

Question 3

3.What does void in int main(void) mean?

Question 4

4.A non-void function ends without return on one branch, and the caller uses the result. This is…

Read more (free)

Open a question to see the answer and why. The first ones are this topic's own quiz, so try the quiz above before you peek.

How does C pass a plain int argument to a function?

Answer: By value (a copy)

C always passes by value; pointers let you pass addresses.

What is a prototype for?

Answer: To declare the function's signature before it is used

The compiler can then check calls.

What does void in int main(void) mean?

Answer: It takes no parameters

The return type is int; (void) means no parameters.

A non-void function ends without return on one branch, and the caller uses the result. This is…

Answer: Undefined behaviour

gcc -Wall warns about it.

What does void as a return type mean?Related

Answer: The function returns nothing

void functions do their job without giving a value back.

From Functions: declare, define, call and return

What is the difference between a parameter and an argument?Related

Answer: A parameter is the name in the method header; an argument is the value passed when calling

Parameters are the placeholders; arguments are the actual values.

From Methods: write once, use many times

Returning &local from a function gives…Related

Answer: A dangling pointer to memory that is no longer valid

The local variable is gone after return.

From Pointers and functions

Does Go support default parameter values?Related

Answer: No

Go has no default values or overloading; use different function names or an options struct.

From Functions and multiple return values

Pass the quiz (60% or more) or mark this topic as done when you are ready.

Your progress is saved on this device only.

Next steps

  1. 4 more topics in “Functions and arrays” before its exam: Scope and storage classes, Recursion, Arrays, 2D arrays and classic array algorithms.
  2. Module 3 exam: Functions and arrays · 12 questions · 25 min, without help. 5 topics of this module still to finish first.
  3. Then the next module, Strings in C. 60 topics left in the course before the final exam.

← Previous: Solving problems with loops