badmaash
badmaash

Reputation: 4845

C++ lambda expression does not compile

I am trying to cin a loop index's value in the loop itself using lambda expression:

#include<iostream>
using namespace std;

int main(){
  for(int a, ([](int & b){cin>>b;})(a); a < 2; ++a);
  return 0;
}

These are the errors when i compile using g++ 4.5 on ubuntu:

forLoopAndCinTest.c++: In function ‘int main()’:
forLoopAndCinTest.c++:5:14: error: expected unqualified-id before ‘[’ token
forLoopAndCinTest.c++:5:14: error: expected ‘)’ before ‘[’ token
forLoopAndCinTest.c++:5:34: error: expected primary-expression before ‘)’ token
forLoopAndCinTest.c++:5:34: error: expected ‘;’ before ‘)’ token
forLoopAndCinTest.c++:5:40: error: name lookup of ‘a’ changed for ISO ‘for’ scoping
forLoopAndCinTest.c++:5:40: note: (if you use ‘-fpermissive’ G++ will accept your code)
forLoopAndCinTest.c++:5:50: error: expected ‘;’ before ‘)’ token

If i use a normal function instead of the lambda, program compiles fine.
Using -fpermissive doesnt help either.
Any ideas?

Upvotes: 4

Views: 2864

Answers (3)

fouronnes
fouronnes

Reputation: 4038

The first part of the for is interpreted as a declaration. We get the very same error when replacing your code by the (almost) equivalent :

int main(){
    int a, ([](int & b){cin>>b;})(a); // This produces the same error
    for(; a < 2; ++a);
    return 0;
}

To answer a comment you made, for (int a, foo() ; ... works, but not like you think it does. It is in fact declaring a function (inside the for scope) that returns an int, and has the name foo. As in :

int a, foo();

Which you should read as :

int a;
int foo();

Upvotes: 2

wilhelmtell
wilhelmtell

Reputation: 58715

That's not how the for look works. You are trying to call a lambda where the compiler expects you to declare an int:

for( int a, int2, ...; a < 2; ++a );

Now,

If i use a normal function instead of the lambda, program compiles fine

Yes, but it's probably not doing what you think it does.

void f(int& b)
{
    cin >> b;
}

// ...
for( int a, f(a); a < 2; ++a );

Here, the loop declares two int variables, named a and f. The loop doesn't call f() as you might expect.

Try this instead:

for( int a; cin >> a && a < 2; ++a );

Upvotes: 5

c-smile
c-smile

Reputation: 27470

After this: for( int a, compiler expects some name (of the variable) - unqualified-id. But in your case it is not so.

Upvotes: 0

Related Questions