Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning value from lambda in the same line with declaration

Sometimes it is easier to represent a value by function, and lambdas are good for this. But is there any way to return value from lambda declaration?

for example:

int i = []{return 2;};

generates an error. How to make that lambda declaration return 2 without any new lines of code?

like image 275
Olexy Avatar asked Jan 01 '23 01:01

Olexy


2 Answers

Like calling any functions using the calling operator(), you need to call the lambda.

int i = []{return 2;}();
//                   ^^
like image 182
JeJo Avatar answered Jan 03 '23 03:01

JeJo


Addtionaly to the answers provided. This is called an immediately-invoked function expression (IIFE), or sometimes, immediately-invoked lambda expression. (FF comes from C++ is widely used in other languages)

int i = []{return 2;}(); // () invokes the lambda AKA call operator
like image 24
Croolman Avatar answered Jan 03 '23 04:01

Croolman