Introduction
Function definition in C provides the actual implementation of a function, including the function body with executable statements. It specifies what the function does when called, containing the complete code that performs the intended operation. Function definitions include the function header and the function body enclosed in braces.
Key Concepts
Function Body: Code block that contains the implementation Return Statement: Returns value to the calling function Local Variables: Variables declared within the function Function Scope: Variables accessible only within the function
Basic Syntax
return_type function_name(parameter_list) {
// Local variable declarations
// Function body statements
// Return statement (if needed)
}
Simple Function Definitions
Functions with Return Values
#include <stdio.h>
// Function to add two numbers
int add(int a, int b) {
int sum = a + b;
return sum;
}
// Function to find maximum of two numbers
int findMax(int x, int y) {
if (x > y) {
return x;
} else {
return y;
}
}
// Function to calculate factorial
int factorial(int n) {
int result = 1;
for (int i = 1; i <= n; i++) {
result *= i;
}
return result;
}
int main() {
printf("5 + 3 = %d\n", add(5, 3));
printf("Max of 10 and 7: %d\n", findMax(10, 7));
printf("Factorial of 5: %d\n", factorial(5));
return 0;
}
Functions without Return Values (void)
#include <stdio.h>
// Function to print a greeting
void greetUser(char name[]) {
printf("Hello, %s! Welcome to our program.\n", name);
}
// Function to print array elements
void printArray(int arr[], int size) {
printf("Array elements: ");
for (int i = 0; i < size; i++) {
printf("%d ", arr[i]);
}
printf("\n");
}
// Function to draw a simple pattern
void drawPattern(int rows) {
for (int i = 1; i <= rows; i++) {
for (int j = 1; j <= i; j++) {
printf("* ");
}
printf("\n");
}
}
int main() {
greetUser("Alice");
int numbers[] = {1, 2, 3, 4, 5};
printArray(numbers, 5);
drawPattern(4);
return 0;
}
Functions with Different Parameter Types
String Processing Functions
#include <stdio.h>
#include <string.h>
// Function to count vowels in a string
int countVowels(char str[]) {
int count = 0;
for (int i = 0; str[i] != '\0'; i++) {
char ch = str[i];
if (ch == 'a' || ch == 'e' || ch == 'i' || ch == 'o' || ch == 'u' ||
ch == 'A' || ch == 'E' || ch == 'I' || ch == 'O' || ch == 'U') {
count++;
}
}
return count;
}
// Function to reverse a string
void reverseString(char str[]) {
int length = strlen(str);
int start = 0;
int end = length - 1;
while (start < end) {
char temp = str[start];
str[start] = str[end];
str[end] = temp;
start++;
end--;
}
}
// Function to check if string is palindrome
int isPalindrome(char str[]) {
int length = strlen(str);
for (int i = 0; i < length / 2; i++) {
if (str[i] != str[length - 1 - i]) {
return 0; // Not a palindrome
}
}
return 1; // Is a palindrome
}
int main() {
char text[] = "programming";
printf("Vowels in '%s': %d\n", text, countVowels(text));
char word[] = "hello";
printf("Original: %s\n", word);
reverseString(word);
printf("Reversed: %s\n", word);
char palindrome[] = "racecar";
printf("'%s' is %s palindrome\n", palindrome,
isPalindrome(palindrome) ? "a" : "not a");
return 0;
}
Mathematical Functions
#include <stdio.h>
// Function to calculate power
double power(double base, int exponent) {
double result = 1.0;
int absExp = (exponent < 0) ? -exponent : exponent;
for (int i = 0; i < absExp; i++) {
result *= base;
}
return (exponent < 0) ? 1.0 / result : result;
}
// Function to calculate area of circle
double circleArea(double radius) {
const double PI = 3.14159265359;
return PI * radius * radius;
}
// Function to convert temperature
double celsiusToFahrenheit(double celsius) {
return (celsius * 9.0 / 5.0) + 32.0;
}
// Function to check if number is prime
int isPrime(int num) {
if (num <= 1) return 0;
if (num <= 3) return 1;
if (num % 2 == 0 || num % 3 == 0) return 0;
for (int i = 5; i * i <= num; i += 6) {
if (num % i == 0 || num % (i + 2) == 0) {
return 0;
}
}
return 1;
}
int main() {
printf("2^3 = %.2f\n", power(2.0, 3));
printf("Area of circle (r=5): %.2f\n", circleArea(5.0));
printf("25°C = %.1f°F\n", celsiusToFahrenheit(25.0));
printf("17 is %sprime\n", isPrime(17) ? "" : "not ");
return 0;
}
Functions with Pointer Parameters
Swapping Values
#include <stdio.h>
// Function to swap two integers
void swapInts(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
// Function to swap two characters
void swapChars(char *x, char *y) {
char temp = *x;
*x = *y;
*y = temp;
}
// Function to modify array elements
void doubleArrayElements(int arr[], int size) {
for (int i = 0; i < size; i++) {
arr[i] *= 2;
}
}
int main() {
int x = 10, y = 20;
printf("Before swap: x=%d, y=%d\n", x, y);
swapInts(&x, &y);
printf("After swap: x=%d, y=%d\n", x, y);
int numbers[] = {1, 2, 3, 4, 5};
printf("Original array: ");
for (int i = 0; i < 5; i++) printf("%d ", numbers[i]);
printf("\n");
doubleArrayElements(numbers, 5);
printf("Doubled array: ");
for (int i = 0; i < 5; i++) printf("%d ", numbers[i]);
printf("\n");
return 0;
}
Functions with Multiple Return Values
Using Pointers for Multiple Returns
#include <stdio.h>
// Function to get both quotient and remainder
void divideNumbers(int dividend, int divisor, int *quotient, int *remainder) {
if (divisor != 0) {
*quotient = dividend / divisor;
*remainder = dividend % divisor;
} else {
*quotient = 0;
*remainder = 0;
printf("Error: Division by zero!\n");
}
}
// Function to find min and max in array
void findMinMax(int arr[], int size, int *min, int *max) {
*min = arr[0];
*max = arr[0];
for (int i = 1; i < size; i++) {
if (arr[i] < *min) *min = arr[i];
if (arr[i] > *max) *max = arr[i];
}
}
// Function to calculate statistics
void calculateStats(float arr[], int size, float *average, float *sum) {
*sum = 0;
for (int i = 0; i < size; i++) {
*sum += arr[i];
}
*average = *sum / size;
}
int main() {
int quotient, remainder;
divideNumbers(17, 5, "ient, &remainder);
printf("17 ÷ 5 = %d remainder %d\n", quotient, remainder);
int numbers[] = {45, 23, 67, 12, 89, 34};
int min, max;
findMinMax(numbers, 6, &min, &max);
printf("Min: %d, Max: %d\n", min, max);
float grades[] = {85.5, 92.0, 78.5, 88.0, 95.5};
float average, sum;
calculateStats(grades, 5, &average, &sum);
printf("Sum: %.1f, Average: %.2f\n", sum, average);
return 0;
}
Recursive Function Definitions
Mathematical Recursion
#include <stdio.h>
// Recursive factorial function
int recursiveFactorial(int n) {
if (n <= 1) {
return 1; // Base case
}
return n * recursiveFactorial(n - 1); // Recursive case
}
// Recursive Fibonacci function
int fibonacci(int n) {
if (n <= 1) {
return n; // Base cases: F(0)=0, F(1)=1
}
return fibonacci(n - 1) + fibonacci(n - 2);
}
// Recursive power function
int recursivePower(int base, int exp) {
if (exp == 0) {
return 1; // Base case: any number^0 = 1
}
if (exp == 1) {
return base; // Base case: base^1 = base
}
return base * recursivePower(base, exp - 1);
}
int main() {
printf("Factorial of 6: %d\n", recursiveFactorial(6));
printf("Fibonacci sequence: ");
for (int i = 0; i < 10; i++) {
printf("%d ", fibonacci(i));
}
printf("\n");
printf("3^4 = %d\n", recursivePower(3, 4));
return 0;
}
Real-World Function Examples
Student Management System
#include <stdio.h>
#include <string.h>
typedef struct {
int id;
char name[50];
float marks[3];
float average;
} Student;
// Function to input student data
void inputStudent(Student *s) {
printf("Enter student ID: ");
scanf("%d", &s->id);
printf("Enter student name: ");
scanf("%s", s->name);
printf("Enter marks for 3 subjects: ");
for (int i = 0; i < 3; i++) {
scanf("%f", &s->marks[i]);
}
}
// Function to calculate average
void calculateAverage(Student *s) {
float sum = 0;
for (int i = 0; i < 3; i++) {
sum += s->marks[i];
}
s->average = sum / 3.0;
}
// Function to display student information
void displayStudent(Student s) {
printf("\n--- Student Information ---\n");
printf("ID: %d\n", s.id);
printf("Name: %s\n", s.name);
printf("Marks: %.1f, %.1f, %.1f\n", s.marks[0], s.marks[1], s.marks[2]);
printf("Average: %.2f\n", s.average);
printf("Grade: %c\n", assignGrade(s.average));
}
// Function to assign grade based on average
char assignGrade(float average) {
if (average >= 90) return 'A';
else if (average >= 80) return 'B';
else if (average >= 70) return 'C';
else if (average >= 60) return 'D';
else return 'F';
}
int main() {
Student student;
inputStudent(&student);
calculateAverage(&student);
displayStudent(student);
return 0;
}
Function Definition Best Practices
Error Handling
#include <stdio.h>
// Function with proper error handling
int safeDivide(int a, int b, int *result) {
if (b == 0) {
printf("Error: Division by zero!\n");
return 0; // Indicate failure
}
*result = a / b;
return 1; // Indicate success
}
// Function with input validation
int validateAndProcess(int input) {
if (input < 0) {
printf("Warning: Negative input converted to positive\n");
input = -input;
}
if (input > 100) {
printf("Warning: Input clamped to maximum value 100\n");
input = 100;
}
return input * 2;
}
Clear and Readable Code
// Good function definition with clear structure
double calculateCompoundInterest(double principal, double rate, int years) {
// Input validation
if (principal <= 0 || rate < 0 || years < 0) {
printf("Error: Invalid input parameters\n");
return 0.0;
}
// Calculate compound interest: A = P(1 + r)^t
double amount = principal;
for (int i = 0; i < years; i++) {
amount *= (1.0 + rate / 100.0);
}
return amount - principal; // Return interest earned
}
Summary
Function definition provides the actual implementation of functions in C, containing the executable code that performs specific tasks. Key components include parameter handling, local variables, return statements, and proper error handling. Well-defined functions should be clear, focused on a single task, handle edge cases appropriately, and follow consistent coding conventions for maintainability and reusability.
Part of BCA Programming with C Course (UGCOA22J201)