A function is a self-contained block of code that performs a specific task. Think of it as a "sub-program" that you can write once and use (call) whenever you need it.
Using functions makes your code modular, easier to read, and reusable.
1. The Three Parts of a Function
To use a function, you generally need these three pieces:
Function Declaration (Prototype): Tells the compiler about the function's name, return type, and parameters (usually at the top of the file).
Function Definition: The actual body of the code where the work happens.
Function Call: When you tell the program to go execute that block.
Simple Code Example
#include <stdio.h> // 1. Declaration (Prototype) int addNumbers(int a, int b); int main() { int x = 5, y = 10, sum; // 3. Function Call sum = addNumbers(x, y); printf("The sum is: %d\n", sum); return 0; } // 2. Definition int addNumbers(int a, int b) { int result = a + b; return result; // Sending the value back to main }
Expected Output:
The sum is: 153. Key Concepts
Return Types
Functions can return a value or nothing at all:
int,float,char: Returns a value of that type.void: Use this keyword if the function doesn't return anything (e.g., just printing a message).
Parameters (Arguments)
These are the inputs you pass to the function.
Formal Parameters: The variables defined in the function header (
int a, int b).Actual Parameters: The real values passed during the call (
x, y)
5. Recursion
A function is "recursive" if it calls itself. This is a powerful way to solve mathematical problems like factorials or Fibonacci sequences.
int factorial(int n) {
if (n <= 1) return 1; // Base case (to stop the loop)
return n * factorial(n - 1); // Recursive call
}