Reusability helps you use the same code again and again without rewriting it. Maintenance makes it easy to fix or improve your code later.
0
0
Reusability and maintenance
Introduction
When you want to use the same function in different parts of your program.
When you need to fix a bug in one place and want the fix to apply everywhere.
When you want to add new features without changing a lot of code.
When you want your code to be clear and easy to understand.
When working in a team so everyone can use shared code easily.
Syntax
C
Use functions to write reusable code blocks.
Example:
return_type function_name(parameters) {
// code here
}
Call the function by its name with arguments:
function_name(arguments);Functions help you write code once and use it many times.
Changing the function code updates all places where it is used.
Examples
This example shows a reusable function
add that adds two numbers.C
int add(int a, int b) { return a + b; } int main() { int sum = add(3, 4); printf("Sum is %d\n", sum); return 0; }
The
greet function is called twice, showing reusability.C
#include <stdio.h> void greet() { printf("Hello!\n"); } int main() { greet(); greet(); return 0; }
Sample Program
This program defines a function square that calculates the square of a number. It is reused to find squares of two different numbers.
C
#include <stdio.h> // Function to calculate the square of a number int square(int num) { return num * num; } int main() { int x = 5; int y = 10; printf("Square of %d is %d\n", x, square(x)); printf("Square of %d is %d\n", y, square(y)); return 0; }
OutputSuccess
Important Notes
Keep functions small and focused on one task for easier reuse.
Use clear names for functions to understand what they do quickly.
Good reusability reduces errors and saves time when updating code.
Summary
Reusability means writing code once and using it many times.
Functions are the main way to achieve reusability in C.
Maintaining reusable code is easier and less error-prone.