Error: Expression must have a constant value

3
  

Expression must have a constant value

I get this error on 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;
}
    
asked by Neon 28.11.2016 в 10:52
source

1 answer

3
int mas[n];

This is what is known as VLA or " Variable Length Array " and 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 were a constant, you could create the array:

const int n = 10;
int mas[n]; // OK

What happens is that not being part of the standard will depend on the compiler to support this feature or not. In some compilers the code will compile and in others not.

To avoid this problem you can use dynamic memory:

int main()
{
    int n;
    cout << "Enter the number of elements: "; cin >> n;
    int* mas = new int[n];
    srand(time(NULL));

    for (int i = 0; i < n; i++) 
    {
        mas[i] = rand()%100-1; 
        cout << " " << mas[i] << "\t";
    }
    cout << endl;

    delete[] mas;

    system("pause");
    return 0;
}

Or a container of the STL:

int main()
{
    int n;
    cout << "Enter the number of elements: "; cin >> n;
    std::vector<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;
}
    
answered by 28.11.2016 / 10:55
source