On this page (10 sections)
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.
main() with 200 lines: reading + calculating + grading + printing, all mixed togetherthe manager
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.
printf(), scanf(), strlen() and main() itself are all functions.Advantages of Functions
| Advantage | Meaning |
|---|---|
| 🧱 Modularity | A large problem is broken into small, manageable parts |
| ♻️ Reusability | Write once, call many times (no copy-paste) |
| 🔍 Easy debugging | If something is wrong, you check one small function |
| 👥 Teamwork | Different programmers can write different functions |
| 📖 Readability | findGrade(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.
| Part | Example | What it does | Where |
| 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. Definition | int 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. Call | result = 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 sum = a + b;
return sum;
}
| int | Return type: the type of value the function gives back (void if none) |
| add | Function name: any valid identifier; use a meaningful verb |
| int a, int b | Parameter 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;
}
Welcome to C functions!
Welcome to C functions!
Welcome to C functions!
void greet()defines a function calledgreet.voidmeans 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;
}
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 thatreturnsends back is stored inresult.- A call is an expression with a value, so we can use it directly inside
printf, as inadd(10, 20).
3️⃣ How a Function Call Works
Let us follow the call add(x, y) from Example 2, step by step.
| 1 | main() runs and reaches result = add(x, y); |
| 2 | Control jumps to add(); a gets 3 and b gets 4 |
| 3 | The body runs: sum = 3 + 4 makes sum 7 |
| 4 | return sum; sends 7 back and ends add() |
| 5 | Back 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.
int x = 3, y = 4;add(x, y);int add(int a, int b)a = 3, b = 4Figure 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;
}
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
- 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, withmain()first and the definitions below it, for readability.
Declaration vs Definition
| Declaration | Definition | |
|---|---|---|
| Purpose | Tells the compiler about the function | Contains the actual code of the function |
Body { } | No | Yes |
| Ends with | Semicolon ; | Closing brace } |
| How many times? | Can be repeated | Exactly once |
| Parameter names | Optional | Required |
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");
}
——————–
square(1) = 1
square(2) = 4
square(3) = 9
square(4) = 16
square(5) = 25
——————–
- The two prototypes at the top (
squareandline) letmain()call both functions even though they are defined later. line(20)prints 20 dashes. It returnsvoid, so we call it as a statement.square(i)returnsi * i, so we use it insideprintf.- 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:
| Type | Parameters | Returns | Example |
|---|---|---|---|
| 1. No input, no output | No | No | void greet() |
| 2. Input, no output | Yes | No | void printTable(int n) |
| 3. No input, output | No | Yes | int getNumber() |
| 4. Input and output | Yes | Yes | int 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);
}
}
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;
}
isEven(10) = 1
isEven(7) = 0
maxOf(8, 15) = 15
factorial(5) = 120
Area of circle (r = 2) = 12.57
isEvenreturns the result ofn % 2 == 0, which is1(true) or0(false).maxOfreturns as soon as it finds the answer. After areturn, the rest of the function does not run.factorialreturns alongbecause factorials grow quickly. It is printed with%ld.circleAreareturns adouble. 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';
}
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
| Function | Its single job | Called |
|---|---|---|
readMarks(subject) | Asks for the marks of one subject and returns them | 3 times (reuse!) |
findAverage(total, count) | Returns the average as a float | once |
findGrade(avg) | Returns the grade letter A, B, C or F | once |
readMarksis 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 / countconverts the total tofloatfirst, so the average keeps its decimals: 232 / 3 = 77.33, not 77.findGradereturns achar. 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; }
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
| Mistake | What goes wrong | Fix |
|---|---|---|
| Calling a function before it is declared or defined | Compiler error or warning about an implicit declaration | Add 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 defined | No semicolon in a definition |
| Missing semicolon after a prototype | Syntax error on the next line | A declaration always ends with ; |
int add(int a, b) | Each parameter needs its own type | int add(int a, int b) |
| Wrong number or order of arguments in the call | Error, or values go to the wrong parameters | Match the prototype exactly |
Forgetting return in a non-void function | Garbage value is returned | Return a value on every path |
Writing int result = greet(); for a void function | A void function has no value to store | Call it as a plain statement |
| Expecting a function to change the caller’s variable | Only 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 call | add(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
returnstatement sends one value back and ends the function. Avoidfunction returns nothing. - Break big programs into small functions, each with one job, and let
main()coordinate them.
🚀 Keep practising: (1) Writeint cube(int n)and print the cubes of 1 to 5. (2) Writeint isPrime(int n)and print all primes up to 30. (3) Writefloat celsiusToFahrenheit(float c). (4) Writeint 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
- Lesson 1: Introduction to C Programming: Overview, Features and Applications
- Lesson 2: The Structure of a C Program: Building Your First Blueprint
- Lesson 3: Identifiers, Keywords and Variables: Naming Things in C Programming
- Lesson 4: Introduction to Algorithms: Thinking Before You Code
- Lesson 5: Introduction to Flowcharts: Drawing the Logic You Already Know
Part 2 · Data Types, Input/Output and Operators
- Lesson 6: Data Types in C: Choosing the Right Box for Every Value
- Lesson 7: Formatted Input and Output in C: Taking Control of printf and scanf
- Lesson 8: Practice Exercise Sheet: Data Types in C
- Lesson 9: Operators and Expressions in C: Assignment, Unary, and Arithmetic
- Lesson 10: Relational, Logical, and Conditional Operators in C
- Lesson 11: Bitwise and Special Operators in C
- Lesson 12: Operator Precedence and Associativity in C
Part 3 · Decisions and Loops
- Lesson 13: Decision and Case Control: if and if-else in C
- Lesson 14: The switch Statement — and switch vs. if-else Ladder
- Lesson 15: The for Loop: Definite Repetition in C
- Lesson 16: while and do-while Loops: Indefinite Repetition in C
- Lesson 17: break and continue in C: Controlling a Loop from the Inside
- Lesson 18: The goto Statement in C: Jumping Around Your Program
Part 4 · Arrays
- Lesson 19: 1-D Arrays in C: Declaration, Address Calculation, Insertion and Deletion
- Lesson 20: Two-Dimensional Arrays in C: Declaration, Initialization and Accessing Elements
- Lesson 21: Matrix Addition and Matrix Multiplication in C
Part 5 · Strings
- Lesson 22: Strings in C: Working with Character Arrays
- Lesson 23: 1-D and 2-D Character Arrays in C: Storing Names and Words
Part 6 · Functions and Scope
- Lesson 24: Functions in C: Declaration and Definition
- Lesson 25: Categories of Functions in C
- Lesson 26: Scope of Variables in C
- Lesson 27: Call by Value in C: How Parameter Passing Works
- Lesson 28: Passing Arrays to Functions in C: Search, Sum and Sort