2. Function Declaration and Definition
2.1 Function Anatomy
A C function consists of several parts:
return_type function_name(parameter_list) {
// Function body
// Local variables
// Statements
return value; // (if return_type is not void)
}
Components:
- Return Type: Data type of the value returned (int, float, char, void, etc.)
- Function Name: Identifier for the function
- Parameter List: Input values (formal parameters)
- Function Body: Statements enclosed in braces
- Return Statement: Returns control and optionally a value
2.2 Function Declaration (Prototype)
Function prototypes declare the function's interface before its actual definition. They are necessary when a function is called before its definition in the source code. This allows the compiler to check for correct usage and enables forward referencing. If a function is defined before it is called, a prototype is not strictly necessary.
Syntax:
return_type function_name(parameter_types);
Examples:
// Function prototypes
int add(int a, int b); // Two int parameters, returns int
float calculate_area(float length, float width); // Two float parameters, returns float
void print_message(void); // No parameters, no return value
char get_grade(int score); // One int parameter, returns char
Important Notes:
- Prototypes end with semicolon (
;
) - Parameter names are optional in prototypes (but recommended for clarity)
- Must match exactly with function definition
2.3 Function Definition
The function definition contains the actual implementation:
#include <stdio.h>
// Function prototype
int multiply(int x, int y);
int main() {
int result = multiply(4, 5);
printf("Result: %d\n", result);
return 0;
}
// Function definition
int multiply(int x, int y) {
int product = x * y;
return product;
}
2.4 void Functions
Functions that don't return a value use void
as the return type:
#include <stdio.h>
void print_header(void);
void print_line(int length);
int main() {
print_header();
print_line(30);
return 0;
}
void print_header(void) {
printf("=== STUDENT MANAGEMENT SYSTEM ===\n");
}
void print_line(int length) {
for (int i = 0; i < length; i++) {
printf("-");
}
printf("\n");
}