Expression must have a constant value
I am getting this error on the line int mas[n]
. Why does the error occur?
int main()
{
int n;
cout << "Enter the number of elements: "; cin >> n;
int mas[n];
srand(time(NULL));
for (int i = 0; i < n; i++)
{
mas[i] = rand()%100-1;
cout << " " << mas[i] << "\t";
}
cout << endl;
system("pause");
return 0;
}
This is what is known as a VLA or " Variable Length Array " and it is a structure that is not allowed in the C++ standard (unlike the C language where it can be used). An array is a VLA if the size of the array is not known at compile time. If
n
it were a constant, you could create the array:What happens is that since it is not part of the standard, it will depend on the compiler to support this feature or not. On some compilers the code will compile and on others it won't.
To avoid this problem you can use dynamic memory:
Or a container of the STL: