Reputation: 53
I am very much new to this feature, I was just reading about Lambda expression in c++ and tried to implement it in a simple program.
int main()
{
std::string name;
int a = 5;
std::cout << "What is your name? ";
getline (std::cin, name);
for([&](){a = 7;};a > 0; a--)
{
std::cout << "Hello, " << name << "!\n";
}
}
but its not working as I thought it will..
My assumption : [&](){a = 7;}
this will change value of variable a to 7 from 5 but its not..
Is there anything wrong in code?? Or just my assumption is incorrect?
Upvotes: 1
Views: 1845
Reputation: 13934
Your assumption is correct provided you invoke it.
[&]: implicitly capture by reference. All local names can be used. All local variables are accessed by reference.
You are able to access the local variable but the lambda itself is not getting called. This is what happening in your code:
Lambda Expression without capture -> functionPtr -> bool (true for non-null functionPtr)
where ->
is implicit conversion
Instead do (lambdaExpression)()
or lambdaExpression()
to invoke it.
Upvotes: 1