Best practice on use of C++ lambda expressions

Viewed 563

I'm studying the C++ lambda expression and I would understand what is better in the following situation.

Suppose I want to write a very simple function to make a sum.

I can write it in the "classic way":

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

// and than call it in some way

int s = sum(1,2);

or in the "modern way":

auto sum = [] (int a, int b) -> int {
  return a+b;
}

// and call it just after its declaration

int s = sum(1,2);

What is better in terms of performance, readabilty, portability for you?

In particular, I have analyzed source codes of other programmers who do for example:

int foo(int a, int b) {
  auto sum = [] (int a, int b) -> int {
    return a+b;
  }
  return sum(a,b);
}

// ...
std::cout << foo(1,2) << std::endl;
// ...

Why should they (and I) prefer the "modern way"? Is not better to sum directly the numbers? What advantages should I expect from this approach?

Thank you!

0 Answers
Related