Categories of Functions in C

Functions in C can be categorized based on the presence or absence of arguments and return values. Each category has its unique use cases, explained below with examples.

1. No Arguments, No Return Values

These functions neither accept any input arguments nor return a value. They are typically used when the task does not require any data from the calling function or when there is no need to return data to the caller.

Example:


#include <stdio.h>
void greet() {
    printf("Hello, welcome to C programming!\n");
}
int main() {
    greet();
    return 0;
}

Output

Hello, welcome to C programming!

2. Arguments but No Return Values

Functions in this category accept arguments as input parameters but do not return a value. They are useful when an operation requires inputs, but the output can be displayed or processed without returning a value.

Example:


#include <stdio.h>
void displaySquare(int num) {
    printf("Square of %d is %dn", num, num * num);
}
int main() {
    displaySquare(5);
    return 0;
}

Output

Square of 5 is 25

3. Arguments with Return Values

These functions accept arguments as input and return a value as output. This is useful for calculations or any process that requires both inputs and an output.

Example :


#include <stdio.h>
int add(int a, int b) {
    return a + b;
}
int main() {
    int result = add(10, 20);
    printf("Sum is: %d\n", result);
    return 0;
}

Output

Sum is: 30

4. No Arguments but Returns a Value

These functions do not take any arguments but return a value to the caller. They are useful when a function generates or retrieves data that doesn't require external input.

Example Code:


#include <stdio.h>
int getRandomNumber() {
    return 42; // Example value
}
int main() {
    int num = getRandomNumber();
    printf("Random number: %d\n", num);
    return 0;
}

Output

Random number: 42

5. Functions that Return Multiple Values

In C, functions cannot directly return multiple values, but this can be achieved using pointers or structures. Here, pointers are used to return multiple values.

Example:


#include <stdio.h>
void getMinMax(int arr[], int size, int *min, int *max) {
    *min = *max = arr[0];
    for (int i = 1; i < size; i++) {
        if (arr[i] < *min) *min = arr[i];
        if (arr[i] > *max) *max = arr[i];
    }
}
int main() {
    int arr[] = {1, 2, 3, 4, 5};
    int min, max;
    getMinMax(arr, 5, &min, &max);
    printf("Min: %d, Max: %d", min, max);
    return 0;
}

Output

Min: 1, Max: 5