0

Imagine I have a .cpp file, which inside has some helper code. I can put that code inside some anonymous namespace. Are there disadvantages to use a lambda function for this? Example:

namespace {

auto to_string_lambda = [](int n) {
  if (n == 0) {
    return "zero";
  }
  else if (n == 1) {
    return "one";
  }

  return "unknown";
};

// VS:

auto to_string_func(int n) {
  if (n == 0) {
    return "zero";
  }
  else if (n == 1) {
    return "one";
  }

  return "unknown";
};

} // anon ns
Maxim Chetrusca
  • 3,262
  • 1
  • 32
  • 28
  • 1
    There's probably no direct disadvantage and the same code probably gets generated but why would you want to do this? – Alan Birtles Aug 04 '23 at 12:02
  • 2
    Do whichever you prefer and find easiest to read. A named function is equivalent if there's no captures; a lambda is much more readable if you need to capture any values. If it's only used once, I often find a named lambda to be effective, and it can be declared right where it's used. – Toby Speight Aug 04 '23 at 12:03
  • thanks, I think I found another question which answers this: https://stackoverflow.com/q/19919754/939050 – Maxim Chetrusca Aug 04 '23 at 12:04
  • That's a different question, putting them inside other functions hides them from the global scope, using lambdas as globals is just extra typing – Alan Birtles Aug 04 '23 at 13:00

0 Answers0