đ ️ Function Declaration, Definition, and Calling in C
Functions in C allow you to divide your code into small, reusable blocks. This helps you avoid repetition, organize code better, and make your programs easier to read and maintain.
đ° What is a Function?
A function is a block of code that performs a specific task. C has both built-in functions (like printf()
) and user-defined functions (functions you create yourself).
đ§ą Parts of a Function
A function typically has 3 main components:
- Declaration (or Prototype): Tells the compiler about the function name, return type, and parameters.
- Definition: Contains the actual code or logic inside the function.
- Calling: Executes the function from
main()
or another function.
đ 1. Function Declaration (Prototype)
return_type function_name(parameter_list);
This line tells the compiler that the function exists, even before its definition.
đ Example:
int add(int, int);
đ 2. Function Definition
return_type function_name(parameter_list) {
// Function body
}
đ Example:
int add(int a, int b) {
return a + b;
}
đ 3. Function Calling
function_name(arguments);
đ Example:
int result = add(5, 3);
✅ Complete Example: Add Two Numbers Using Function
#include <stdio.h>
// Function declaration
int add(int, int);
int main() {
int num1, num2, sum;
printf("Enter two numbers: ");
scanf("%d %d", &num1, &num2);
// Function call
sum = add(num1, num2);
printf("Sum = %d\n", sum);
return 0;
}
// Function definition
int add(int a, int b) {
return a + b;
}
đ¯ Why Use Functions?
- đ Code reuse: Write once, use multiple times
- đ Better readability and structure
- đ Easy debugging and testing
- đ Modular design: Break complex tasks into small parts
đ§ Function Types in C
Based on return value and parameters:
- With return, with parameters
- With return, without parameters
- Without return, with parameters
- Without return, without parameters
đš Example: Without return, without parameters
void greet() {
printf("Hello, welcome!\n");
}
đš Example: With return, no parameters
int getNumber() {
return 42;
}
⚠️ Common Mistakes to Avoid
- ❌ Using a function before declaring or defining it
- ❌ Mismatching return types or parameters
- ❌ Forgetting to return a value in non-void functions
đ§Š Practice Problems
- Create a function that checks whether a number is even or odd.
- Write a function to calculate factorial of a number.
- Create a function to find the maximum of three numbers.
- Make a function that converts Celsius to Fahrenheit.
āĻোāύ āĻŽāύ্āϤāĻŦ্āϝ āύেāĻ:
āĻāĻāĻি āĻŽāύ্āϤāĻŦ্āϝ āĻĒোāϏ্āĻ āĻāϰুāύ