Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

error: variable-sized object may not be initialized #394

Closed
jetcoder opened this issue Apr 3, 2021 · 3 comments
Closed

error: variable-sized object may not be initialized #394

jetcoder opened this issue Apr 3, 2021 · 3 comments

Comments

@jetcoder
Copy link

jetcoder commented Apr 3, 2021

Full error message:

/home/insights/insights.cpp:8:10: error: variable-sized object may not be initialized
        int arr[num] {};
                ^~~
1 error generated.
Error while processing /home/insights/insights.cpp.

During following code running:

#include <iostream>

int main()
{
	int num;
	std::cin >> num;	
	
	int arr[num] {};
	
	for (auto& item : arr)
	{
		std::cout << item << " ";
	}
	std::cout << std::endl;
		
}

The error is shown for C++ standards from 11 to 20a.

@i-ky
Copy link

i-ky commented Apr 3, 2021

As far as I know, variable length array is not a part of C++ standard, it is a GCC extension. To an extent, clang supports VLA too, but it does not support initialization of such arrays.

@jetcoder
Copy link
Author

jetcoder commented Apr 3, 2021

There is an example in C++14 standard (N3690):
§ 8.3.4

void f(unsigned int n) {
    int a[n]; // type of a is “array of runtime bound of int”
}

But indeed, looks like clang doesn't support VLAs.

@andreasfertig
Copy link
Owner

Hello @jetcoder,

VLA's are special. They work, even in Clang, if you remove the braced-init. As the size of a VLA is unknown at compile-time, the compiler cannot produce an initializer for it at compile-time. Hence, the following works:

int num;
std::cin >> num;	
	
int arr[num];

As this is not a C++ Insights bug, I'm closing this issue.

Andreas

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants