1

In the code listed below, "LambdaTest" fails with the following error on Clang only:

shared/LambdaTest.cpp:8:31: error: variable 'array' with variably 
modified type cannot be captured in a lambda expression
    auto myLambdaFunction = [&array]()
                          ^
shared/LambdaTest.cpp:7:9: note: 'array' declared here
    int array[length];

The function "LambdaTest2" which passes the array as a parameter instead of capturing compiles fine on G++/Clang.

// Compiles with G++ but fails in Clang
void LambdaTest(int length)
{
    int array[length];
    auto myLambdaFunction = [&array]()
    {
        array[0] = 2;
    };
    myLambdaFunction();
}

// Compiles OK with G++ and Clang
void LambdaTest2(int length)
{
    int array[length];
    auto myLambdaFunction = [](int* myarray)
    {
        myarray[0] = 2;
    };
    myLambdaFunction(array);
}

Two questions:

  1. What does the compiler error message "variable 'array' with variably modified type cannot be captured in a lambda expression" mean?

  2. Why does LambdaTest fail to compile on Clang and not G++?

Thanks in advance.

COMPILER VERSIONS:
*G++ version 4.6.3
*clang version 3.5.0.210790

Chadness3
  • 196
  • 1
  • 1
  • 11

3 Answers3

3

int array[length]; is not allowed in Standard C++. The dimension of an array must be known at compile-time.

What you are seeing is typical for non-standard features: they conflict with standard features at some point. The reason this isn't standard is because nobody has been able to make a satisfactory proposal that resolves those conflicts. Instead, each compiler has done their own thing.

You will have to either stop using the non-standard feature, or live with what a compiler happens to do with it.

M.M
  • 138,810
  • 21
  • 208
  • 365
1

VLA (Variable-length array) is not officially supported in C++.
You can instead use std::vector like so:

void LambdaTest(int length)
{
    std::vector<int> array(length);
    auto myLambdaFunction = [&array]()
    {
        array[0] = 2;
    };
    myLambdaFunction();
}
Yuval Ben-Arie
  • 1,280
  • 9
  • 14
1

Thanks to both answers above for pointing out that VLAs are non-standard. Now I know what to search for.

Here are more are related links to the subject.

Why aren't variable-length arrays part of the C++ standard?

Why no VLAS in C++

Chadness3
  • 196
  • 1
  • 1
  • 11