0

Is it considered as good practice to assign lambda expressions in C++ to a variable? I know from python, that it isn't good practice

Which is more preferable to use: lambda functions or nested functions ('def')?

which makes perfect sense to me, because it makes no sense to give an anonymous function a name. However, I have seen very often in C++ that lambda is assigned to a variable, like here for example

https://en.cppreference.com/w/cpp/language/lambda https://en.cppreference.com/w/cpp/ranges/drop_view

Is this considered as good practice in C++? From this post here

What is a lambda expression in C++11?

I conclude, it can be also seen as very convenient way to define functors. So it looks like lambda is in C++ considered as more than just an anonymous function.

bilaljo
  • 358
  • 1
  • 6
  • 13
  • 2
    Its good practice to make your code readable. If assigning a lambda to a variable makes it more readable, do it. – tkausl Apr 13 '23 at 14:14
  • 2
    Note that the question you linked asks for better choice between two options: lambda or nested function. C++ doesn't allow nested function definitions, so a lambda is the only possibility for named definition of another function. – Yksisarvinen Apr 13 '23 at 14:16
  • Opinion based perhaps. – Jason Apr 13 '23 at 14:16
  • 1
    note that python has style guides that come with the language. C++ doesnt have that. There are many things considered as "pythonic" or "non pythonic" which are merely based on some style guide which is based on opinions – 463035818_is_not_an_ai Apr 13 '23 at 14:19

1 Answers1

2

In short, it usually is. It improves your code by making it more readable. Of course, don't use lambda for lambda's own sake.

rtcha0x
  • 36
  • 3