Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

issues with for loops in lambdas

I am currently rewriting a small project i written some time ago, and am replacing function pointers with std::function and lambdas.

While doing this i stumbled over an issue with for loops in lambdas. in Visual Studio 2010 (with SP1) generates strange errors when for loops are used inside lambdas, IF the lambda is defined at file scope:

#include <iostream>

auto print_sum =
    []( int n )
    {
        int sum=0;
        // line below generates: 
        //   error C2143: syntax error : missing ')' before ';'
        for( int i=1; i<=n; ++i ) 
            sum += i;
        std::cout << sum << "\n";
    };

int main()
{
    print_sum(3);
    return 0;
}

following snippet however compiles fine:

#include <iostream>

int main()
{
    auto print_sum =
        []( int n )
        {
            int sum=0;
            for( int i=1; i<=n; ++i )
                sum += i;
            std::cout << sum << "\n";
        };
    print_sum(3);
    return 0;
}

Both snippets compile fine using MinGW GCC 4.7.

Has anyone else observed this behaviour aswell? Is this a bug in the lambda implementation of the Visual Studio? Do you know any workarounds?

Edit:
bug report on microsoft connect:
https://connect.microsoft.com/VisualStudio/feedback/details/660742/error-with-for-loops-in-file-scope-lamdas-c-0x#details

like image 853
smerlin Avatar asked Apr 08 '11 18:04

smerlin


1 Answers

I can verify this behavior on Visual Studio 2010 RTM. It appears to be limited to just for loops as the following compiles just fine.

auto print_sum =
    [](int n)
    {
        int sum=0;
        int i = 1;
        while (i <= n)
        {
            sum += i;
            i++;
        }
        std::cout << sum << "\n";
    };

I would definitely alert microsoft to this issue by filing a bug on connect

  • http://connect.microsoft.com

Note: I don't 100% know if this is a bug but evidence suggests that it is

like image 129
JaredPar Avatar answered Sep 19 '22 22:09

JaredPar