C ++ lambda expression not compiling

I am trying to cin value of the loop index in the loop itself using the lambda expression:

 #include<iostream> using namespace std; int main(){ for(int a, ([](int & b){cin>>b;})(a); a < 2; ++a); return 0; } 

These are errors when compiling with 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 lambda, the program compiles fine.
Using -fpermissive does not help.
Any ideas?

+4
source share
3 answers

This is not what the for looks like. You are trying to call 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 lambda, the program compiles fine

Yes, but he probably doesn't do what you think he 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 does not call f() , as you might expect.

Try this instead:

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

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

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

To answer your comment, for (int a, foo() ; ... works, but not in the way you think. It actually declares a function (inside the for scope) that returns an int, and has the name foo. As in:

 int a, foo(); 

What you should read as:

 int a; int foo(); 
+2
source

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

0
source

All Articles