» Quick Introduction to C++ » 1. Basics » 1.7 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 <iostream>

// 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;
    std::cout << "The factorial of " << num << " is: " << factorial(num) << std::endl;
    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 <iostream>

// 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);
    std::cout << "Square of " << num << " is: " << result << std::endl;
    return 0;
}

Variadic

A variadic function is a function that can accept a variable number of arguments. The cstdarg header provides a set of macros and types to work with such functions.

#include <iostream>
#include <cstdarg>

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

    // Initialize the va_list
    va_list args;

    // Start processing the arguments
    va_start(args, count);

    // Loop through the arguments and accumulate the sum
    for (int i = 0; i < count; ++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
    std::cout << "Sum: " << sum(3, 1, 2, 3) << std::endl;
    std::cout << "Sum: " << sum(5, 10, 20, 30, 40, 50) << std::endl;

    return 0;
}

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

Lambda Expressions

Lambda expressions in C++ allow you to define anonymous functions or function objects (closures) directly within your code. Lambda expressions provide a concise way to create functions, especially for short-lived and local purposes.

#include <iostream>

int main() {
    // Lambda expression to add two numbers
    auto add = [](int a, int b) {
        return a + b;
    };

    // Using the lambda to add two numbers
    int result = add(3, 5);

    std::cout << "Result of adding 3 and 5: " << result << std::endl;

    // Lambda expression to multiply two numbers
    auto multiply = [](int x, int y) -> int {
        return x * y;
    };

    // Using the lambda to multiply two numbers
    result = multiply(4, 6);

    std::cout << "Result of multiplying 4 and 6: " << result << std::endl;

    // Lambda expression with no parameters
    auto sayHello = [] {
        std::cout << "Hello, Lambda!" << std::endl;
    };

    // Using the lambda with no parameters
    sayHello();

    return 0;
}

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