C Programming · December 1, 2026

Functions in C: Declaration and Definition

Module II · Functions · Function Declaration and Definition


🎯 Why Do We Need Functions?

Imagine a restaurant where one person takes the order, cooks, serves, cleans the tables and prepares the bill. It would be slow, messy, and a single mistake could spoil everything. A real restaurant divides the work: a waiter, a chef, a cashier. Every person does one job well.

A C program works the same way. So far, all our code was inside main(). That is fine for 20 lines, but a real program may have thousands of lines. The solution is to divide a large program into smaller, named pieces called functions.

One big program
main() with 200 lines: reading + calculating + grading + printing, all mixed together
⬇ divide into functions ⬇
main()
the manager
⬇ calls ⬇
readMarks()
reads the marks
findAverage()
calculates average
findGrade()
decides the grade
printResult()
shows the result

Figure 1: Instead of one huge main(), we write small functions and let main() call them.

📌 A function is a named block of code that performs one specific task and can be used (called) whenever we need it. You have already used functions: printf(), scanf(), strlen() and main() itself are all functions.

Advantages of Functions

AdvantageMeaning
🧱 ModularityA large problem is broken into small, manageable parts
♻️ ReusabilityWrite once, call many times (no copy-paste)
🔍 Easy debuggingIf something is wrong, you check one small function
👥 TeamworkDifferent programmers can write different functions
📖 ReadabilityfindGrade(avg) is easier to understand than ten lines of if-else

1️⃣ Three Things You Must Know

To use your own function in C, three things are involved: declaration, definition and call.

PartExampleWhat it doesWhere
1. Declaration
(prototype)
int add(int a, int b);Tells the compiler the name, return type and parameters. Ends with a semicolon. No body.Before main()
2. Definitionint add(int a, int b) { return a + b; }The real function: header + body with the code. No semicolon after the header.After main() (or before it)
3. Callresult = add(3, 4);Runs the function with actual values (arguments) and receives the returned value.Inside main() or another function

Figure 2: The three parts of using a function: declare it, define it, call it.

2️⃣ Function Definition

The function definition is where you write the function itself: what it is called, what it needs, and what it does.

return_type function_name(parameter_list)
{
    // body: statements
    return value;      // not needed for void
}
int add(int a, int b)
{
    int sum = a + b;
    return sum;

}
intReturn type: the type of value the function gives back (void if none)
addFunction name: any valid identifier; use a meaningful verb
int a, int bParameter list: the inputs, each with its type
{ … }Function body: the statements that do the work, ending with return

Figure 3: The four parts of a function definition.

Return Type

The type of the value the function sends back: int, float, double, char, and so on. If the function does not return anything, the return type is void.

Parameters

Parameters are the inputs of the function, written inside the brackets with the type of each one. A function may have no parameters, one, or many, separated by commas. int add(int a, int b) has two parameters. Note that every parameter needs its own type: int add(int a, b) is an error.

Body and return

The body is enclosed in { }. The return statement sends one value back to the caller and immediately ends the function.

Example 1: Your First Function (no input, no output value)

The simplest function takes nothing and returns nothing: its type is void.

#include <stdio.h>

void greet() {
    printf("Welcome to C functions!\n");
}

int main() {
    greet();
    greet();
    greet();
    return 0;
}
🖥️ Output:
Welcome to C functions!
Welcome to C functions!
Welcome to C functions!
  • void greet() defines a function called greet. void means it returns nothing.
  • Its body has one statement, a printf.
  • The definition by itself does nothing. The code runs only when we call the function with greet();. We called it 3 times, so the message appears 3 times. This is reusability.
  • The program starts at main(), not at the first function in the file.

Example 2: A Function that Returns a Value

#include <stdio.h>

int add(int a, int b) {
    int sum = a + b;
    return sum;
}

int main() {
    int x = 3, y = 4, result;

    result = add(x, y);
    printf("Sum = %d\n", result);
    printf("add(10, 20) = %d\n", add(10, 20));
    return 0;
}
🖥️ Output:
Sum = 7
add(10, 20) = 30
  • int add(int a, int b) takes two integers and returns an integer.
  • result = add(x, y); calls the function. The value that return sends back is stored in result.
  • A call is an expression with a value, so we can use it directly inside printf, as in add(10, 20).

3️⃣ How a Function Call Works

Let us follow the call add(x, y) from Example 2, step by step.

1main() runs and reaches result = add(x, y);
2Control jumps to add(); a gets 3 and b gets 4
3The body runs: sum = 3 + 4 makes sum 7
4return sum; sends 7 back and ends add()
5Back in main(): result becomes 7 and main() continues with the next line

Figure 4: What happens when main() calls add(x, y).

Actual Arguments and Formal Parameters

The values you write in the call are actual arguments. The variables in the definition are formal parameters. When the function is called, the value of each argument is copied into the matching parameter, in order: first argument to first parameter, second to second.

main()
int x = 3, y = 4;
add(x, y);
➜ copies 3 and 4 ➜
add()
int add(int a, int b)
a = 3, b = 4
Actual arguments (in the call)  |  Formal parameters (in the definition)

Figure 5: Actual arguments (x, y) are copied into formal parameters (a, b).

The names do not need to match (x and y versus a and b), but the number, order and types must.

Example 3: A Function Cannot Change the Caller’s Variable

Because only a copy of the value is passed, the function works on its own copy. This is called call by value.

#include <stdio.h>

void tryToChange(int n) {
    n = 100;
    printf("Inside function : n = %d\n", n);
}

int main() {
    int n = 5;

    printf("Before the call : n = %d\n", n);
    tryToChange(n);
    printf("After the call  : n = %d\n", n);
    return 0;
}
🖥️ Output:
Before the call : n = 5
Inside function : n = 100
After the call : n = 5

Inside tryToChange, the parameter n became 100, but the n in main() is a different variable, so it is still 5 after the call. (Changing the caller’s variable needs pointers, which you will learn later.)

4️⃣ Function Declaration (Prototype)

The compiler reads the file from top to bottom. If main() calls a function that is defined below it, the compiler has not seen that function yet and does not know what it returns or what it needs. The function declaration (also called the function prototype) solves this: it introduces the function in advance.

int add(int a, int b);       // declaration: ends with a semicolon
💡 Think of a prototype as a menu card. It tells the compiler the name of the dish, what you must give (parameters) and what you get back (return type), without showing the recipe. The recipe is the definition.
  • The parameter names are optional in a declaration: int add(int, int); is also valid. Types are compulsory.
  • The declaration must match the definition in name, return type and parameter types.
  • If the function is defined before main(), a separate declaration is not needed. Most programmers still put prototypes at the top, with main() first and the definitions below it, for readability.

Declaration vs Definition

DeclarationDefinition
PurposeTells the compiler about the functionContains the actual code of the function
Body { }NoYes
Ends withSemicolon ;Closing brace }
How many times?Can be repeatedExactly once
Parameter namesOptionalRequired

Example 4: Declaration at the Top, Definition at the Bottom

#include <stdio.h>

/* Declarations (prototypes) */
int square(int n);
void line(int count);

int main() {
    int i;

    line(20);
    for (i = 1; i <= 5; i++) {
        printf("square(%d) = %d\n", i, square(i));
    }
    line(20);
    return 0;
}

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

void line(int count) {
    int i;
    for (i = 0; i < count; i++)
        printf("-");
    printf("\n");
}
🖥️ Output:
——————–
square(1) = 1
square(2) = 4
square(3) = 9
square(4) = 16
square(5) = 25
——————–
  • The two prototypes at the top (square and line) let main() call both functions even though they are defined later.
  • line(20) prints 20 dashes. It returns void, so we call it as a statement.
  • square(i) returns i * i, so we use it inside printf.
  • Remove the prototypes and the compiler complains (or guesses wrongly) about the unknown functions. That is why prototypes matter.

5️⃣ Types of Functions

Based on the parameters and the return value, a function can be of four kinds:

TypeParametersReturnsExample
1. No input, no outputNoNovoid greet()
2. Input, no outputYesNovoid printTable(int n)
3. No input, outputNoYesint getNumber()
4. Input and outputYesYesint add(int a, int b)

Use () or (void) for “no parameters”. Type 4 is the most useful, since the function gets data from the caller and gives the answer back.

Example 5: Input but No Return Value

#include <stdio.h>

void printTable(int n);

int main() {
    int num;

    printf("Enter a number: ");
    scanf("%d", &num);

    printTable(num);
    return 0;
}

void printTable(int n) {
    int i;
    for (i = 1; i <= 5; i++) {
        printf("%d x %d = %d\n", n, i, n * i);
    }
}
🖥️ Output:
Enter a number: 7
7 x 1 = 7
7 x 2 = 14
7 x 3 = 21
7 x 4 = 28
7 x 5 = 35

printTable(int n) receives the number, prints five lines of its table, and returns nothing, so its type is void. The user’s input is read in main() and passed on to the function.

Example 6: Several Functions that Return Different Types

A function may return any type. The type in front of the function name must match the value you return.

#include <stdio.h>

int isEven(int n);
int maxOf(int a, int b);
long factorial(int n);
double circleArea(double r);

int main() {
    printf("isEven(10)   = %d\n", isEven(10));
    printf("isEven(7)    = %d\n", isEven(7));
    printf("maxOf(8, 15) = %d\n", maxOf(8, 15));
    printf("factorial(5) = %ld\n", factorial(5));
    printf("Area of circle (r = 2) = %.2f\n", circleArea(2.0));
    return 0;
}

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

int maxOf(int a, int b) {
    if (a > b)
        return a;
    return b;
}

long factorial(int n) {
    long f = 1;
    int i;
    for (i = 2; i <= n; i++)
        f *= i;
    return f;
}

double circleArea(double r) {
    return 3.14159 * r * r;
}
🖥️ Output:
isEven(10) = 1
isEven(7) = 0
maxOf(8, 15) = 15
factorial(5) = 120
Area of circle (r = 2) = 12.57
  • isEven returns the result of n % 2 == 0, which is 1 (true) or 0 (false).
  • maxOf returns as soon as it finds the answer. After a return, the rest of the function does not run.
  • factorial returns a long because factorials grow quickly. It is printed with %ld.
  • circleArea returns a double. We print it with %.2f (two decimal places).

6️⃣ Converting a Large Program into Smaller Functions

This is the real purpose of functions. Suppose we must read the marks of three subjects, find the total and average, and decide the grade. We give each job to its own function. Then main() reads like a short story.

Example 7: Student Result Using Functions

#include <stdio.h>

int readMarks(int subject);
float findAverage(int total, int count);
char findGrade(float avg);

int main() {
    int m1, m2, m3, total;
    float avg;

    m1 = readMarks(1);
    m2 = readMarks(2);
    m3 = readMarks(3);

    total = m1 + m2 + m3;
    avg = findAverage(total, 3);

    printf("\nTotal   = %d\n", total);
    printf("Average = %.2f\n", avg);
    printf("Grade   = %c\n", findGrade(avg));
    return 0;
}

int readMarks(int subject) {
    int m;
    printf("Enter marks of subject %d: ", subject);
    scanf("%d", &m);
    return m;
}

float findAverage(int total, int count) {
    return (float)total / count;
}

char findGrade(float avg) {
    if (avg >= 75) return 'A';
    if (avg >= 60) return 'B';
    if (avg >= 40) return 'C';
    return 'F';
}
🖥️ Output:
Enter marks of subject 1: 78
Enter marks of subject 2: 85
Enter marks of subject 3: 69

Total = 232
Average = 77.33
Grade = A
FunctionIts single jobCalled
readMarks(subject)Asks for the marks of one subject and returns them3 times (reuse!)
findAverage(total, count)Returns the average as a floatonce
findGrade(avg)Returns the grade letter A, B, C or Fonce
  • readMarks is written once but called three times with different subject numbers. Without a function we would have copied the same four lines three times.
  • (float)total / count converts the total to float first, so the average keeps its decimals: 232 / 3 = 77.33, not 77.
  • findGrade returns a char. The average is 77.33, which is at least 75, so the grade is A.
  • Each function can now be tested separately. If the grade is wrong, we only look inside findGrade.

Example 8: A Menu-Driven Calculator

Functions and switch work very well together: each menu option becomes one small function.

#include <stdio.h>

int add(int a, int b);
int subtract(int a, int b);
int multiply(int a, int b);

int main() {
    int x, y, choice;

    printf("Enter two numbers: ");
    scanf("%d %d", &x, &y);
    printf("1. Add  2. Subtract  3. Multiply\n");
    printf("Enter your choice: ");
    scanf("%d", &choice);

    switch (choice) {
        case 1: printf("Result = %d\n", add(x, y)); break;
        case 2: printf("Result = %d\n", subtract(x, y)); break;
        case 3: printf("Result = %d\n", multiply(x, y)); break;
        default: printf("Invalid choice\n");
    }
    return 0;
}

int add(int a, int b)      { return a + b; }
int subtract(int a, int b) { return a - b; }
int multiply(int a, int b) { return a * b; }
🖥️ Output:
Enter two numbers: 12 5
1. Add 2. Subtract 3. Multiply
Enter your choice: 3
Result = 60

The user entered 12 and 5 and chose option 3, so multiply(12, 5) was called and returned 60. To add another operation later we write one more function and one more case. The existing code does not change.

⚠️ Common Mistakes

MistakeWhat goes wrongFix
Calling a function before it is declared or definedCompiler error or warning about an implicit declarationAdd a prototype at the top
Semicolon after the definition header: int add(int a, int b); { ... }The body becomes a stray block and the function is not definedNo semicolon in a definition
Missing semicolon after a prototypeSyntax error on the next lineA declaration always ends with ;
int add(int a, b)Each parameter needs its own typeint add(int a, int b)
Wrong number or order of arguments in the callError, or values go to the wrong parametersMatch the prototype exactly
Forgetting return in a non-void functionGarbage value is returnedReturn a value on every path
Writing int result = greet(); for a void functionA void function has no value to storeCall it as a plain statement
Expecting a function to change the caller’s variableOnly a copy is changed (see Example 3)Return the new value and store it
Writing the type in the call: add(int x, int y);Types belong in the declaration and definition, not in a calladd(x, y);

❓ Frequently Asked Questions

Q: Is main() also a function?
Yes. It is the special function where every C program starts. The operating system calls it, and its return 0; reports success.

Q: Can a function return more than one value?
Not directly. A function returns at most one value. (Returning several values is possible through pointers or arrays, which come later.)

Q: Can one function call another?
Yes. In Example 7, main() calls three functions. A function can call any function that has been declared or defined above it, and even itself (recursion, a later topic).

Q: Do I always have to write the prototype?
Only when the function is defined after the place where it is called. Writing prototypes at the top is a good habit in every program.

✅ Key Takeaways

  • A function is a named block of code that does one task. Functions make programs modular, reusable and easy to debug.
  • The definition has a return type, a name, parameters and a body: int add(int a, int b) { ... }.
  • The declaration (prototype) tells the compiler about the function in advance, ends with ; and has no body.
  • A call runs the function: add(x, y);. Arguments are copied into parameters in order (call by value).
  • The return statement sends one value back and ends the function. A void function returns nothing.
  • Break big programs into small functions, each with one job, and let main() coordinate them.
🚀 Keep practising: (1) Write int cube(int n) and print the cubes of 1 to 5. (2) Write int isPrime(int n) and print all primes up to 30. (3) Write float celsiusToFahrenheit(float c). (4) Write int minOf3(int a, int b, int c). (5) Rewrite the simple-interest program with a separate function for the calculation. Always write the prototype first!
All 29 lessons in this series (open course page)

Part 1 · Getting Started

Part 2 · Data Types, Input/Output and Operators

Part 3 · Decisions and Loops

Part 4 · Arrays

Part 5 · Strings

Part 6 · Functions and Scope

Part 7 · Pointers