C Functions

A function in C is a named block of code that performs a task. Functions help you organize a program into smaller parts that can be called whenever you need them.

You have already used functions such as printf. Now you will write your own functions.

Function Syntax

A function definition includes a return type, a function name, parentheses, and a body inside braces.

#include <stdio.h>

void sayHello(void)
{
    printf("Hello from a function!\n");
}

int main(void)
{
    sayHello();
    sayHello();

    return 0;
}

Output:

Hello from a function!
Hello from a function!

The function sayHello is defined before main. Inside main, each statement sayHello(); calls the function, so its body runs twice.

Return Type And Function Name

The word before the function name is the return type. A function with return type void does its work without sending a value back to the caller.

The parentheses after the name hold the function’s parameters. In this lesson, void inside the parentheses means the function takes no parameters. Parameters are covered in the next lesson.

Returning A Value

A function can calculate a result and send it back with return. The returned value must match the function’s return type.

#include <stdio.h>

int getScore(void)
{
    return 95;
}

int main(void)
{
    int score = getScore();

    printf("Score: %d\n", score);
    printf("Bonus score: %d\n", getScore() + 5);

    return 0;
}

Output:

Score: 95
Bonus score: 100

The function getScore returns an int. You can store that value in a variable, print it, or use it as part of a larger expression.

Function Declarations

C needs to know about a function before it is called. One way is to place the full function definition above main. Another common way is to put a function declaration, also called a prototype, above main and the full definition later.

#include <stdio.h>

int getYear(void);

int main(void)
{
    printf("Year: %d\n", getYear());

    return 0;
}

int getYear(void)
{
    return 2026;
}

Output:

Year: 2026

The line int getYear(void); tells the compiler that a function named getYear exists, takes no parameters, and returns an int. The semicolon is required for the declaration.

Why Use Functions?

  • Functions make programs easier to read by giving names to tasks.
  • Functions reduce repeated code because one function can be called many times.
  • Functions make testing and fixing code easier because each part has a smaller job.
  • main is also a function; it is where a C program starts running.

Quick Rules

  • Define or declare a function before calling it.
  • Use void as the return type when a function does not return a value.
  • Use return to send a value back from a non-void function.
  • End a function call with a semicolon, such as sayHello();.

The key idea is that functions let you name and reuse blocks of code. Next, you will learn how to pass values into functions with parameters.