Function Declaration and Definition in C Programming (Complete Guide)
This tutorial explains functions in C, including function declaration, definition, and calling. It helps beginners understand how to write reusable, modular code, improving readability and maintainability of C programs.
1. What Are Functions in C
Functions are blocks of code that perform a specific task.
They allow:
- Reusability of code
- Modular programming
- Better readability
Example: printf() is a built-in function.
2. Function Declaration (Prototype)
A function declaration tells the compiler about:
- Function name
- Return type
- Parameter types
Syntax:
return_type function_name(parameter_list);
Example:
int add(int a, int b); // Function declaration
Notes:
- Usually placed before main()
- Also called a function prototype
3. Function Definition
A function definition provides the actual body of the function.
Syntax:
return_type function_name(parameter_list) {
// code
return value; // if return_type is not void
}
Example:
int add(int a, int b) {
return a + b;
}
4. Calling a Function
A function is called from main() or other functions.
Example Program:
#include <stdio.h>
// Function declaration
int add(int a, int b);
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;
}
Sample Output:
Enter two numbers: 10 20
Sum = 30
5. Points to Remember
- Declaration before usage helps the compiler check arguments
- Definition contains the actual task logic
- Return type can be
int,float,char, orvoid - Functions can take zero or more parameters