Caution while using variable length array in lambda in C++17.

Revision en1, by nitin12384, 2023-02-15 08:02:23

Say you have a variable length array declared in a function, and you try to initialize it using memset in a lambda function, like this.

int n; cin>>n;
int cnt[n];
auto reset = [&](){
    memset(cnt, 0, sizeof(cnt));

It will not work correctly because sizeof(cnt) will return sizeof(int*) instead of n*sizeof(int).
That is because variable length array seems to decay to pointer when using labmda functions.

But surprisingly, this happens only in C++17, not in C++20.
In C++ 20, sizeof(cnt) will return n*sizeof(int).

Here is code demonstating this. You can try to run it in custom invocation.

Demo Code
Output in GNU G++17 7.3.0
Output in GNU G++20 11.2.0 (64 bit, winlibs)

Just be cautious while using arrays in lambda functions. I got wrong answer in a problem due to this, and it took me a lot of time to figure out that this was causing the issue.

Anyone is welcome to post comment of any related facts/insight, or maybe some explanations about why this happens, and why this doesn't happens in C++20.

Tags array, c++, c++20, lambda


  Rev. Lang. By When Δ Comment
en1 English nitin12384 2023-02-15 08:02:23 2131 Initial revision (published)