Lesson 21: Introduction to Functions
Functions are blocks of code designed to perform a specific task. They promote modularity, reusability, and readability.
Components of a Function
1. Function Declaration (Prototype)
This tells the compiler about the function's name, return type, and parameters before it is used. Often placed in a header file or at the top of the source file.
Syntax: return_type function_name(parameter_list);
c int add(int a, int b); // Prototype
2. Function Definition
The actual code block that implements the function's logic.
c int add(int a, int b) { // Definition header int sum = a + b; return sum; // Returns an integer value }
3. Function Call
Executing the function by using its name and providing arguments.
c #include <stdio.h>
// 1. Declaration int add(int a, int b);
int main() { int result; // 3. Function Call result = add(10, 5); printf("The sum is: %d\n", result); return 0; }
// 2. Definition int add(int a, int b) { return a + b; }
Note: If the function definition appears before main(), a separate prototype might not be necessary, but prototypes are essential for multi-file programs.