In C programming, function definition refers to writing the actual body of a function — the block of code that performs a specific task.
It tells the compiler what the function does when it is called.
A function definition includes:
- Return Type
- Function Name
- Parameter List (optional)
- Function Body enclosed in
{ }
1. Syntax of Function Definition
return_type function_name(parameter_list) {
// statements
// return value (if required)
}
2. Components Explained
a) Return Type
Specifies what type of value the function will return.
Common return types:
intfloatchardoublevoid(returns nothing)
b) Function Name
An identifier that follows C naming rules.
Examples:add, display, calculateAverage
c) Parameter List
Represents input values passed to the function.
Examples:
int add(int x, int y)
void display(int n)
float average(float a, float b, float c)
If a function takes no parameters:
void greet()
d) Function Body
Contains the code statements that define the function’s behavior.
3. Example: Function Definition with Return Value
int add(int a, int b) {
int result = a + b;
return result;
}
Here:
- Return type →
int - Function name →
add - Parameters →
aandb - Body → calculates and returns the sum
4. Example: Function Definition Without Return Value
void greet() {
printf("Hello, welcome to C programming!");
}
The function returns nothing and only prints a message.
5. Example: Function Definition Without Parameters
int getNumber() {
return 10;
}
No inputs are required — the function always returns 10.
6. Example: Function Definition With Multiple Parameters
float divide(float x, float y) {
return x / y;
}
This function returns a floating-point result.
7. Full Program Demonstrating Function Definition
#include <stdio.h>
// Function definition
int square(int n) {
return n * n;
}
int main() {
int num = 5;
int ans = square(num); // Function call
printf("Square of %d is %d", num, ans);
return 0;
}
8. Notes About Defining Functions
- A function can be defined above
main()or below it. - If defined after
main(), you must write a function declaration (prototype) beforemain(). - Every C program must have one and only one
main()function. - Function names must be unique within the same scope.
Citations
🔗 View other articles about C Programming:
https://savanka.com/category/learn/c-programming/
🔗 External C Documentation:
https://www.w3schools.com/c/