Sobes.tech
Junior — Middle

What is the advantage of using anonymous functions compared to regular functions in programming?

sobes.tech AI

Answer from AI

Anonymous functions (lambda expressions) have several advantages over regular named functions:

  • Locality: they allow defining a function right where it is needed, improving code readability and maintainability.
  • Convenience of passing: they are easily passed as arguments to other functions, simplifying work with callbacks and functional style.
  • Closures: they can capture variables from the surrounding context, which is not possible with regular functions without additional constructs.

Example in C++:

#include <iostream>
#include <vector>
#include <algorithm>

int main() {
    std::vector<int> nums = {1, 2, 3, 4, 5};
    int factor = 2;
    std::for_each(nums.begin(), nums.end(), [factor](int &n) { n *= factor; });
    for (int n : nums) std::cout << n << " "; // Will output: 2 4 6 8 10
}

Here, the anonymous function multiplies each element by factor, capturing it from the external context.