What do these statement does?

What do these statement does?
i can’t understand the right-hand of =(equal to) does. can anyone help me with it??

Statement :
auto Submask=[&](int A,int B{return((A&B)==A);};

Thanks in advance !!

1 Like

The statement

auto Submask=[&](int A,int B){return((A&B)==A);};

defines a C++11 lambda function called Submask, capturing (completely unnecessarily, as it it a pure function) local variables by reference, and taking two int parameters A and B. The return type can be deduced by the compiler to be bool (so actually, this is probably C++14).

The result of invoking the lamba with arguments A and B will be true if and only if all bits set in A are also set in B .

6 Likes

what is lamda funtion ? i heard about it but don’t know what is it.

in C++, you can look at it (from the point of view of usefulness) as a function that can be defined within a function (as happens here), or as an “anonymous” function that can be defined and invoked without giving it a name, like e.g.

vector<Dog> dogs = /* list of Dog objects */;
sort(dogs.begin(), dogs.end(), [](const auto& dog1, const auto& dog2) { return dog1.age < dog2.age; }); // Sort the vector dogs in order of increasing age.

Se e.g. https://www.drdobbs.com/cpp/lambdas-in-c11/240168241

10 Likes

one last question, what is the use of that [ ] bracket?
is it return type or something else?

No, that’s the captures list which describes how the lambda is allowed to refer to local variables in the enclosing scope.

For example, in

#include <iostream>

using namespace std;

int main()
{
    int C = 5;
    auto blah = [](const int A, const int B) { return A + B + C; };
    blah(2, 3);
}

we have a compiler error - the body of the lambda makes use of the variable C in the scope enclosing the lambda, but the lambda’s capture list is empty. Adding C to the capture list fixes the error:

    auto blah = [C](const int A, const int B) { return A + B + C; };

We could also use [&] (as your example does) to make all local variables accessible, by reference, to the body of the lamba, or [=] to make all local variables accessible, by value, to the body of the lambda, as shortcuts, but this usage is discouraged as it can lead to unintended side-effects :slight_smile:

8 Likes

Thanks…! :raised_hands:

Can we add pass multiple variables like this [C,D,E] ? and is it pass by reference or value ?

1 Like

Yes, you can capture multiple local variables, each by reference or value e.g.

#include <iostream>

using namespace std;

int main()
{
    int C = 5, D = 6, E = 3;
    auto blah = [C, &D, E](const int A, const int B) { D++; return A + B + C + D + E; };
    E = 10'000;
    cout << blah(2, 3) << endl;
    cout << "D: " << D << endl;
}

Here, C and E are captured by value, and D is captured by reference.

9 Likes