» Quick Introduction to C » 1. Basics » 1.6 Functions

Functions

A function is a self-contained block of code that performs a specific task or set of tasks. Functions provide a way to organize and modularize code, making it more readable, maintainable, and reusable.

#include <stdio.h>

// Function to calculate the factorial of a number
int factorial(int n) {
    if (n == 0 || n == 1) {
        return 1;
    } else {
        return n * factorial(n - 1);
    }
}

int main() {
    int num = 5;
    printf("The factorial of %d is: %d\n", num, factorial(num));
    return 0;
}

Inline

inline keyword is used to suggest to the compiler that it should attempt to insert the code of a function directly into the calling code, rather than generating a function call. This can lead to performance improvements in certain situations by avoiding the overhead of a function call.

#include <stdio.h>

// Inline function definition
static inline int square(int x) {
    return x * x;
}

int main() {
    int num = 5;
    // Call to the inline function
    int result = square(num);
    printf("Square of %d is: %d\n", num, result);
    return 0;
}

Variadic

A variadic function in C is a function that can accept a variable number of arguments. The stdarg.h header provides a set of macros and types to work with such functions. One common example of a variadic function is the printf function itself.

#include <stdio.h>
#include <stdarg.h>

// Variadic function to calculate the sum of integers
int sum(int num, ...) {
    int result = 0;

    // Declare a va_list to hold the variable arguments
    va_list args;

    // Initialize the va_list to point to the first variable argument
    va_start(args, num);

    // Loop through the variable arguments and calculate the sum
    for (int i = 0; i < num; i++) {
        result += va_arg(args, int);
    }

    // Clean up the va_list
    va_end(args);

    return result;
}

int main() {
    // Call the variadic function with different numbers of arguments
    printf("Sum: %d\n", sum(3, 1, 2, 3));
    printf("Sum: %d\n", sum(5, 10, 20, 30, 40, 50));

    return 0;
}

Note that the sum function needs at least one fixed argument (num) to determine the number of variable arguments. The va_arg macro is used to retrieve each variable argument based on its type.

Code Challenge

Write a C program that defines a variadic function named calculateAverage to calculate the average of a variable number of arguments.

Loading...
> code result goes here
Prev
Next