Functions are blocks of code designed to perform a specific task. They make programs modular, readable, and reusable.
1. Components of a Function
A function generally consists of:
- Function Declaration (Prototype)
int add(int, int); // Declares function before use
- Function Definition
int add(int a, int b) {
return a + b;
}
- Function Call
int sum = add(5, 3);
2. Function Parameters
- Actual Parameters (Arguments): Values passed during function call.
- Formal Parameters: Variables in function definition that receive values.
void greet(char name[]) {
printf(“Hello %s”, name);
}
greet(“Alice”); // “Alice” is actual parameter
3. Library Function vs User-Defined Function
- Library Functions: Predefined functions (e.g., printf(), scanf()).
- User-Defined Functions: Created by the programmer to perform specific tasks.
4. Different Forms of Functions
- No input, no output
void greet() { printf(“Hello”); }
greet();
- Input, no output
void printSquare(int n) { printf(“%d”, n*n); }
printSquare(5);
- No input, output
int getRandom() { return 42; }
int x = getRandom();
- Input and output
int add(int a, int b) { return a + b; }
int sum = add(3, 4);
5. Recursion
- A function that calls itself.
- Must have a base condition to stop recursion.
int factorial(int n) {
if(n == 0) return 1;
return n * factorial(n-1);
}
6. Passing Arrays and Strings to Functions
- Array: Pass by reference by default.
void printArray(int arr[], int size) {
for(int i=0;i<size;i++) printf(“%d “, arr[i]);
}
- String: Passed like a character array.
void printString(char str[]) { printf(“%s”, str); }
7. Call by Value & Call by Reference
- Call by Value: Copies value to function. Original variable unchanged.
void increment(int x) { x++; }
- Call by Reference: Passes address; original variable can be changed.
void increment(int *x) { (*x)++; }
8. Macros
- Preprocessor directives that define constants or code snippets.
#define PI 3.14159
#define SQUARE(x) ((x)*(x))
9. Storage Class
Determines the scope, lifetime, and visibility of variables:
- auto → Default, local variables.
- register → Suggests storage in CPU register.
- static → Preserves value between function calls.
- extern → Refers to global variables in other files.
Key Takeaways
- Functions make programs modular, readable, and reusable.
- Components: Declaration, Definition, Call.
- Parameters: Actual vs. Formal.
- Library functions are predefined; user-defined functions are programmer-created.
- Forms: No input/output, input only, output only, input & output.
- Recursion: Functions can call themselves with a base case.
- Arrays and strings are typically passed by reference.
- Call by Value copies values; Call by Reference allows modification.
- Macros define constants or reusable code snippets.
- Storage classes control variable scope and lifetime.