Advanced Concept of Functions

Last Updated: Jan 2026


Function Overloading

Function overloading is a feature in C that allows multiple functions to have the same name but different parameters.

int add(int a, int b) {
    return a + b;
}

int add(int a, int b, int c) {
    return a + b + c;
}

int main() {
    int result1 = add(5, 10);
    int result2 = add(5, 10, 15);
    printf("Result 1: %d\n", result1);
    printf("Result 2: %d\n", result2);
    return 0;
}

Passing Arrays to Functions

In C, arrays decay into pointers when passed to functions. You pass the address of the first element, meaning array modifications inside a function always affect the original array.

Passing 1D Arrays

Because the function receives a raw pointer, it doesn't know how big the array is—you should always pass the array size as an extra parameter.

#include <stdio.h>

void printArray(int* arr, int size) {
    for (int i = 0; i < size; i++) {
        printf("%d ", arr[i]);
    }
    printf("\n");
}

int main() {
    int arr[] = {1, 2, 3, 4, 5};
    int size = sizeof(arr) / sizeof(arr[0]);
    printArray(arr, size);
    return 0;
}

Passing 2D Arrays

#include <stdio.h>

void printArray(int** arr, int rows, int cols) {
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < cols; j++) {
            printf("%d ", arr[i][j]);
        }
        printf("\n");
    }
    printf("\n");
}

int main() {
    int arr[2][3] = {{1, 2, 3}, {4, 5, 6}};
    printArray(arr, 2, 3);
    return 0;
}

Array of Function Pointers (Dispatch Table)

You can create an array of function pointers to call different functions based on a condition.

#include <stdio.h>

int add(int a, int b) {
    return a + b;
}

int subtract(int a, int b) {
    return a - b;
}

int main() {
    int (*functions[2])(int, int) = {add, subtract};
    int result1 = functions[0](5, 10);
    int result2 = functions[1](5, 10);
    printf("Result 1: %d\n", result1);
    printf("Result 2: %d\n", result2);
    return 0;
}

Another Example

#include <stdio.h>

void step1(void) { printf("Step 1: Init\n"); }
void step2(void) { printf("Step 2: Processing\n"); }
void step3(void) { printf("Step 3: Cleanup\n"); }

int main(void) {
    // Array of 3 function pointers taking void and returning void
    void (*pipeline[3])(void) = {step1, step2, step3};

    // Execute pipeline sequence in a loop
    for (int i = 0; i < 3; i++) {
        pipeline[i]();
    }

    return 0;
}

Passing Strings to Functions

Strings in C are null-terminated ('\0') char arrays, so you don't need to pass an explicit size parameter.

#include <stdio.h>

void printString(const char* str) {
    printf("%s\n", str);
}

int main() {
    char str[] = "Hello, World!";
    printString(str);
    return 0;
}


Liked This Tutorial

Scan QR Code To Leave A Review Or

Click Here To Leave A Review
Scan QR