Introduction
A function in C is a block of code that performs a specific task. Functions improve modularity, readability, and reusability of programs. Instead of writing the same code repeatedly, a function can be called multiple times.
Key Points
1. Function Definition
- Syntax:
returnType functionName(parameters) { // code } - Example:
int add(int a, int b) { return a + b; }
2. Function Declaration (Prototype)
- Tells the compiler about the function’s name, return type, and parameters before main function.
- Syntax:
int add(int, int);
3. Function Call
- Executes the function.
- Example:
int result = add(5, 3);
4. Types of Functions
- Built-in functions – Provided by C standard library, e.g.,
printf(),scanf(),sqrt() - User-defined functions – Created by programmer to perform specific tasks
5. Function Return Types
- void → Does not return any value
- Non-void → Returns a value (int, float, char, etc.)
6. Advantages
- Modular programming: Divide program into manageable sections
- Reusability: Use same function in multiple programs
- Easier debugging: Fix errors in one place
Example Code
#include <stdio.h>
// Function declaration
int add(int a, int b);
int main() {
int sum;
sum = add(10, 5); // Function call
printf("Sum: %d", sum);
return 0;
}
// Function definition
int add(int a, int b) {
return a + b;
}