Expression must have a constant value

Feb 7, 2017 at 6:50pm
Hi, I don´t know why when I try to build this code with Visual Studio it returns an error, but if I do it with Code Blocks it runs perfect. Im using Visual Studio 15

1
2
3
4
5
6
7
8
9
10
11
#include <iostream>

int main()
{
	unsigned numpos = 3;
	unsigned solucion[numpos][9];
	solucion[1][1] = 1;
	
	std::cout << solucion[1][1] << std::endl;
	
}

expression must have a constant value
Error C2131 expression did not evaluate to a constant
Error C3863 array type 'unsigned int [numpos][9]' is not assignable

I don´t know why it runs in code blocks but don´t in Visual...

Thans so much for your help!
Last edited on Feb 7, 2017 at 7:02pm
Feb 7, 2017 at 7:23pm
you cannot, in C++, allocate an array from a variable because arrays have a fixed size created at run time.

either make numpos a constant, or make solucion a pointer. You can allocate a pointer of variable size and resize it if you must.



Welcome to c++... where illegal code can work fine in some compilers and IDES and not in others. Actually, legal code can have some problems as well, portability is a bit of a problem with the language at times.
Last edited on Feb 7, 2017 at 7:24pm
Feb 7, 2017 at 8:39pm
Variable-length array (VLA) is a feature that exists in C but not in C++.

GCC (which I assume is the compiler that you were using with Code::Blocks) allows VLA as an extension by default, but if you explicitly request standard conformance by using the compiler flag -pedantic-errors you will get an error.

1
2
unsigned numpos = 3;
unsigned solucion[numpos][9]; // error: ISO C++ forbids variable length array ‘solucion’  

https://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html#index-pedantic-316
Feb 8, 2017 at 3:08pm
Thanks so much for your answers.
As you have said its VLA and Visual C++ don´t support it.
https://msdn.microsoft.com/en-us/library/zb1574zs.aspx

So I decided to solve with the vector container

std::vector<std::vector<unsigned>> solucion;

Thanks so much jonnin and Peter87!
Topic archived. No new replies allowed.