educative.io

Lack of explanation about lambda functions in C++ basics course

Hello everyone,
I am currently following the C++ Basics course but I think there is a lack of explanation about them.
Particularly in the code that is provided in this part. The code is the following one.
I added std::cout to print what the lambda function is doing.

My problem is that I do not understand how b is defined and where its value is coming from.
Could someone explain it to me please?
Thank you in advance.

Code:
#include
#include

std::function<int(int)> makeLambda(int a){    
    return [a](int b){ 
        std::cout << "a : " << a << std::endl;
        std::cout << "b : " << b << std::endl;
        std::cout << "a + b : " << a + b << std::endl;
        return a + b; };
}

int main(){

auto add5 = makeLambda(5);    

auto add10 = makeLambda(10);     

add5(10) == add10(5);               

}

Result:

a : 5
b : 10
a + b : 15
a : 10
b : 5
a + b : 15

Hello @Lind,

Basically, the lambda function has three basic things.

  • []: Captures the used variables.
  • (): Necessary for parameters.
  • ->: Necessary for complex lambda functions.
  • {}: Function body, per default const.

So in the above example, the [a] is used to capture the value passed the first time. Means that when we call makeLambda(5), the value 5 is captured by the a, and when we call the makeLambda(10), then the value 10 is assigned to b and we get the result 15.
Similarly when this line is add5(10) == add10(5); is executed the value 10 is captured by a and the value 5 is assigned to b.

I hope I have answered your query; please let me know if you still have any confusion.

Thank You :blush:

Hello @Abdul_Mateen,

Thank you for your reply!
I think I still miss the point actually.

If I understand what you have explained when the line auto add5 = makeLambda(5) is run you said that a=5.
It is when the line auto add10 = makeLambda(10) is run that b=10.
However, I do not understand well. When makeLambda(5) is running, this line std::cout << "b : " << b << std::endl; is proceeded rignt ?
So how can b equal 10 (and it is printed b=10) if auto add10 = makeLambda(10) has not been run yet?

Thank you in advance for your answer.


Course: Educative: Interactive Courses for Software Developers
Lesson: Educative: Interactive Courses for Software Developers