Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

captured variable hides passed variable in lambda. how to unhide?

Tags:

c++

c++11

Consider this example:

int main()
{
    int a = 100;
    std::cout<<[=,&a](int a,int b){return a+b;}(99,1);
    return 0;
}

The output is 101 instead of my expectation of 100.

I cant specify as so [&a,=] as it gives error.

How do i avoid the name hiding and refer to the parameter. i know changing the name is the option but i'm curious. also reference to standard will be helpful

EDIT: i'm using gcc 4.7.1

EDIT:

here is the ideone link showing the demo. i used c++ 4.7.2 complier there
ideone

like image 908
Koushik Shetty Avatar asked May 28 '13 17:05

Koushik Shetty


3 Answers

I could not find anything related to lambdas in the standard that would indicate your results are the expected behavior. I agree with Andy's comment that this is a bug in GCC. GCC 4.7.2 on Linux, GCC 4.7.2 from MinGW, and GCC 4.8.0 from MinGW produce the same results as in the question but VC++10 and VC++11 produce the expected results.

You should consider filing a bug report

like image 73
Captain Obvlious Avatar answered Nov 14 '22 23:11

Captain Obvlious


Since the parameter doesn't have a scope that you can name, you can't use scope resolution operator to disambiguate, nor this or any other such means. Therefore, it's impossible to disambiguate this scenario the way you want. You'll just have to not give your variables horrible and clashing names.

like image 24
Puppy Avatar answered Nov 14 '22 21:11

Puppy


How do I print out the outer a here, but in the inner scope?

int a = 1;
{
    int a = 2;
    cout << a << endl;
}

You either change the name of one of the variables - or you don't.

The same goes for your lambda.

(I apologize that I can't reference the standard like you requested - I don't have it.)

like image 36
Timothy Shields Avatar answered Nov 14 '22 22:11

Timothy Shields