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.
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.