Skip to content
Tutorials Center
My learning

Topics

Lesson 28 of 135 ยท Functions

Functions

Learn how to define and call functions in C, choose return types, write void functions, and split a program into small named pieces that are easy to test.

A function is a named block of code that does one job. You've used functions since your first program: main is one, and printf, scanf and strlen are functions from the standard library. In this chapter you'll write your own. Instead of one long main that does everything, you'll build programs from small pieces like average, is_leap_year or print_receipt, each of which you can read, test and reuse on its own.

This lesson covers the basics: how to define a function, how a call works, what return types mean, and when a function returns nothing at all (void). The next lessons go deeper into parameters and return values, prototypes and headers, recursion and scope.

Why write functions?

Imagine a program that prints a box around three different messages. Without functions, you'd copy the drawing code three times. When you later want a different border character, you change it in three places and probably miss one. A function solves several problems at once:

  • No repetition. Write the code once, call it as often as you like. Fix a bug once and it's fixed everywhere.
  • Names explain intent. if (is_leap_year(year)) says what's being checked. The arithmetic behind it can live somewhere else.
  • Smaller pieces are easier to get right. You can test a 10-line function with a few inputs. Testing a 300-line main is much harder.
  • Teamwork and reuse. Functions can move into separate files and libraries (Multi-File Programs); the whole C standard library is just a big collection of functions.

Defining and calling a function

A function definition has a header and a body:

C
return_type function_name(parameter_list) {
    /* body: the statements that do the work */
}
  • The return type says what kind of value the function hands back, such as int or double, or void for nothing.
  • The name follows the usual identifier rules. C programmers use snake_case, usually starting with a verb: print_line, compute_total.
  • The parameter list declares the inputs, each with a type and a name, separated by commas. A function with no inputs writes void here.
  • The body is a block in braces.

To call a function, write its name followed by the arguments in parentheses. Here's a complete program with two functions of its own:

C Your first functions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

square takes one int and returns an int. print_line takes the width and prints a row of dashes; it returns nothing, so its return type is void. Both are defined above main, so the compiler already knows them when it reaches the calls. (If you want main first, you declare the functions with prototypes; that's the topic of Declarations, Prototypes and Headers.)

Two words are easy to mix up:

  • A parameter is the variable in the definition: n in int square(int n).
  • An argument is the value you pass in a call: 3 in square(3).

What happens during a call

When the program reaches square(3), it does the following:

  1. It evaluates each argument (here just 3).
  2. It creates the parameter n as a brand-new local variable and initializes it with that value. The function works on its own copy.
  3. It runs the body of square from the top.
  4. When return n * n; executes, the function ends immediately and the value 9 replaces the call expression in the caller.
  5. The caller continues where it left off: printf receives 9.

Each call gets fresh local variables. When the function returns, they disappear. The bookkeeping lives on the call stack, which Recursion and Memory Layout explore. You can watch calls nest by printing as you go:

C Following the flow of calls

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The indentation in the output shows the nesting: main calls add_three, which calls add twice. Each call to add gets its own a, b and sum, and add_three waits until each one returns.

Return types and return statements

A function with a non-void return type must hand back a value with return expression;. The value is converted to the return type if needed, the same way an assignment would convert it (see Type Conversions and Casts).

return ends the function immediately, even in the middle of a loop. That makes "early return" a natural way to express decisions:

C Early returns

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

1900 is a common year (divisible by 100 but not 400), 2000 and 2024 are leap years, and 2025 isn't. Each rule in is_leap_year returns as soon as it decides, so there's no need for nested else branches. days_in_month returns straight out of the switch, which means no break statements are needed. And functions call other functions freely: days_in_month reuses is_leap_year instead of repeating the rule.

The bool type comes from <stdbool.h> (in C23, bool, true and false are keywords and the header is optional). Functions that answer a yes/no question are often named is_... or has_... and return bool; see Booleans.

Every path must return a value

If a non-void function can reach its closing brace without a return, the caller receives garbage, and using that value is undefined behavior. GCC warns about this with -Wall:

C
int sign(int x) {
    if (x > 0) {
        return 1;
    } else if (x < 0) {
        return -1;
    }
}   /* warning: control reaches end of non-void function */

sign(0) falls off the end. The fix is a final return 0;. Treat this warning as an error: it's always a real bug. The only exception is main: since C99, reaching the end of main behaves like return 0;. Writing it explicitly is still good style.

void functions

A function that does something rather than computing a value, such as printing, has the return type void. It may use a bare return; to leave early, or simply run to its closing brace:

C void functions

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

print_bar takes a string and a number. The const char * type means "a pointer to characters this function won't modify", which is how C passes text around; Strings explains it fully. %-8s prints the label left-aligned in 8 columns.

print_banner(void) takes no parameters. In C, write void in the parentheses for that. An empty list () means something different in older C standards ("unspecified parameters"), which Declarations, Prototypes and Headers explains. In C23, () finally means "no parameters" too, but (void) works in every standard.

You can't use the "result" of a void function: int x = print_banner(); is a compile error. On the other hand, C lets you ignore the result of a non-void function. That's normal for printf, which returns the number of characters printed, but ignoring the result of scanf or malloc hides errors. C23 adds the [[nodiscard]] attribute, which makes the compiler warn when a caller ignores a return value:

C
[[nodiscard]] int parse_port(const char *text);   /* C23 */

parse_port("8080");   /* warning: ignoring return value of 'parse_port',
                         declared with attribute 'nodiscard' */

Designing good functions

Knowing the syntax is the easy part. These habits make functions pleasant to use:

  • One job per function. If you need "and" to describe it ("reads the file and sorts it and prints it"), split it.
  • Short. Many good C functions fit on one screen. Long ones usually hide smaller functions waiting to be extracted.
  • Name the result or the action. average, count_vowels and is_valid_email for functions that compute; print_report and save_settings for functions that act.
  • Compute in one place, print in another. A function that returns the average is useful everywhere; one that prints it is useful only where that exact output is wanted.
  • Avoid hidden inputs. A function that reads global variables is harder to understand and test than one that receives everything as parameters (see Scope and Storage Classes).

Here's that advice in action, with the calculation separated from the output:

C Compute, then print

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

average and count_above know nothing about printing, so they could be reused in a program that draws charts or writes files. print_report combines them. Arrays are passed with their length because a C function can't find out the length of an array argument by itself; Pointers and Arrays shows why.

Common mistakes

  • Calling a function without parentheses. print_banner; names the function but doesn't call it. GCC only warns statement with no effect, so read your warnings.
  • Forgetting to use the return value. square(5); on its own line computes 25 and throws it away.
  • Defining a function inside another function. Standard C doesn't allow nested functions (GCC has an extension, but don't rely on it). Define every function at file level.
  • Expecting a function to change its arguments. The function works on copies, so void reset(int n) { n = 0; } changes nothing in the caller. Parameters and Return Values shows how to do it with pointers.
  • Missing return on some path in a non-void function.

Nested functions (a GCC extension)

In standard C, every function is defined at file level, outside any other function. Some languages (Pascal, Python, JavaScript) let you define a function inside another one, and GCC offers the same thing for C as an extension. You may meet it in older Linux code, so it's worth recognizing, and worth knowing why you shouldn't write it yourself.

A nested function is defined inside a block, and it can read and change the local variables of the function that contains it:

C A nested function (GCC only)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

GCC compiles this without complaint and prints total = 20, because add can see total. Now look at the problems:

  • It isn't C. The standard doesn't allow it. With -Wpedantic, GCC itself warns ISO C forbids nested functions, and Clang, MSVC and most other compilers reject the code with an error. (Clang has a different extension called blocks.) C++ doesn't allow it either, though C++ lambdas solve the same problem; see C and C++.
  • Taking its address costs safety. When a nested function is passed to another function as a function pointer, GCC builds a small piece of code called a trampoline on the stack at run time. That requires an executable stack, a protection that modern systems switch off because attackers love it. The linker warns about it:
C Passing a nested function triggers an executable stack

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The program prints 107, but the build output includes a linker warning like requires executable stack (because the .note.GNU-stack section is executable). On some hardened systems such a program refuses to start at all.

The portable fix is always simple: define the helper at file level, and pass it the data it needs as parameters. For callbacks, the C convention is an extra void *context parameter that carries the caller's data, which you'll see in Function Pointers and in library functions like qsort:

C
static void add(int *total, int amount) {   // standard C: the data is a parameter
    *total += amount;
}

So treat nested functions as something to recognize when reading code, not something to use: they tie your program to one compiler and, in their most useful form, weaken its security.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does this print? int twice(int x) { return x * 2; } ... printf("%d", twice(twice(3)));

    The inner call twice(3) returns 6, and the outer call twice(6) returns 12.
  2. 2. In int area(int w, int h) called as area(4, 5), what are w and h?

    w and h are parameters, local variables of the function. The values 4 and 5 in the call are the arguments that initialize them.
  3. 3. What happens when a return statement runs inside a loop in a function?

    return ends the whole function at once, no matter how deeply nested in loops it is.
  4. 4. What is wrong with int sign(int x) { if (x > 0) return 1; if (x < 0) return -1; }?

    When x is 0 neither return runs. Using the missing value is undefined behavior, and GCC warns "control reaches end of non-void function".
  5. 5. Which header is correct for a function that takes no arguments and returns nothing, in every C standard?

    void as the return type means no value, and void in the parameter list means no parameters. An empty () only means "no parameters" in C23.

Summary

  • A function has a return type, a name, a parameter list and a body; you call it with its name and arguments in parentheses.
  • Parameters are local variables initialized with copies of the arguments; each call gets fresh ones.
  • return value; ends the function immediately and hands the value back. Every path of a non-void function must return a value.
  • void as a return type means "returns nothing"; (void) as the parameter list means "takes nothing".
  • Define functions before use (or declare them with prototypes, coming up next).
  • Good functions do one job, have descriptive names and separate computing from printing.

Next: Parameters and Return Values, where you'll see exactly how data flows into and out of functions.