0

I have this following code:

int main()
{
    string s = "LOL";
    auto f = [s](string s) // [=](string s) //****
    { cout << s << endl; };
    f("WTF");
}

My question is about the line marked with //****.

In the first case (with [s]) the output is "LOL".

In the second case (with [=]) the output is "WTF".

I don't understand why.

I thought that [=] tells the lambda to capture all the scope's variables. Why is there a difference in the behavior?

Kobi T
  • 417
  • 6
  • 12
  • 1
    Don't keep reusing the same variable name. That will probably make the issue clearer. This seems almost certainly like a scoping issue. – sircodesalot Sep 19 '17 at 18:38
  • The parameter shadows any captured variables. – user0042 Sep 19 '17 at 18:38
  • Any reason your naming the lambda parameter and the capture the same? Makes knowing what is going on harder when you do. – NathanOliver Sep 19 '17 at 18:38
  • The same variable's name it in order to understand the mechanism behind it (had similar question in exam). – Kobi T Sep 19 '17 at 18:39
  • @KobiT, You should update your question. It currently sounds like you want to know why the output is different, not fine details of captures. – chris Sep 19 '17 at 18:41
  • It's the same. I wanna know why there's a different output in between [s] and [=] in this specific case. – Kobi T Sep 19 '17 at 18:42
  • @user0042 Why doesn't it shadow when using [=]? – Kobi T Sep 19 '17 at 18:45
  • I can't reproduce your described behavior. With VS 2017, it prints "WTF" in both cases. – MooseBoys Sep 19 '17 at 18:47
  • @MooseBoys that's weird. Maybe some end case that is undefined in the language? – Kobi T Sep 19 '17 at 18:49
  • @user0042 my question is not duplication of the linked one. Mine is about the difference between [vars] and [=] as exampled in the attached code. – Kobi T Sep 19 '17 at 18:53
  • _@KobiT_ Ask @Praetorian, I voted to close for other reasons. – user0042 Sep 19 '17 at 18:54
  • @user0042 what reasons? If I may ask – Kobi T Sep 19 '17 at 18:55
  • Last time I've checked the case `[s](string s)` [was considered ill-formed](http://eel.is/c++draft/expr.prim.lambda#capture-5) (this would actually make sense). – user7860670 Sep 19 '17 at 18:57
  • @KobiT As explained in the duplicate and the link in the comment above, `[s](std::string s){...}` is ill-formed, so there's no point in speculating about the difference between `[s]` and `[=]` in your example. – Praetorian Sep 19 '17 at 19:29

0 Answers0