C Functions
Overview
Functions are the building blocks of C programs. They allow code reuse, modularization, and better organization.
Function Declaration and Definition
Function Declaration (Prototype)
c
return_type function_name(parameter_list);Function Definition
c
return_type function_name(parameter_list) {
// function body
return value;
}Example Functions
Simple Function
c
#include <stdio.h>
// Function declaration
int add(int a, int b);
int main() {
int result = add(5, 3);
printf("Result: %d\n", result); // Output: Result: 8
return 0;
}
// Function definition
int add(int a, int b) {
return a + b;
}Function with Multiple Parameters
c
float calculate_average(int a, int b, int c) {
return (float)(a + b + c) / 3;
}Function with No Parameters
c
void print_hello() {
printf("Hello, World!\n");
}Function with No Return Value
c
void print_number(int num) {
printf("Number: %d\n", num);
}Function Parameters
Pass by Value
c
void modify_value(int x) {
x = 100; // Only modifies local copy
}Pass by Reference (using pointers)
c
void modify_value(int *x) {
*x = 100; // Modifies original value
}Best Practices
- Use descriptive function names
- Keep functions small and focused
- Use prototypes for better code organization
- Document functions with comments
- Handle edge cases properly