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)

return_type function_name(parameter_list);

Function Definition

return_type function_name(parameter_list) {
    // function body
    return value;
}

Example Functions

Simple Function

#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

float calculate_average(int a, int b, int c) {
    return (float)(a + b + c) / 3;
}

Function with No Parameters

void print_hello() {
    printf("Hello, World!\n");
}

Function with No Return Value

void print_number(int num) {
    printf("Number: %d\n", num);
}

Function Parameters

Pass by Value

void modify_value(int x) {
    x = 100;  // Only modifies local copy
}

Pass by Reference (using pointers)

void modify_value(int *x) {
    *x = 100;  // Modifies original value
}

Best Practices

  1. Use descriptive function names
  2. Keep functions small and focused
  3. Use prototypes for better code organization
  4. Document functions with comments
  5. Handle edge cases properly