Home > Software engineering >  Constant value error in array declaration
Constant value error in array declaration

Time:06-10

While writing my code on Visual Studio 2022, I came across the error (E0028) that the expression must have a constant value in line 11.

#include <iostream>
using namespace std;

int main() 
{
    int n;
    
    cout<<"Enter"<<endl;
    cin>>n;
    
    int a[n];     //error line
    
    for(int i = 0; i<n; i  )
    {
        cin>>a[i];
    }
    for(int i = 0; i<n; i  )
    {
        cout<<" "<<a[i];
    }
    
    return 0;
}

But when I put the same code in any online compiler, it worked fine. How does this happen? Also how to resolve the issue in Visual Studio 2022.

What I have tried:

I think that the best way to deal with this is dynamic array allocation using vectors, but I would like to hear your views. Also, why don't we have the same error in online compilers?

CodePudding user response:

The size of an array variable must be compile time constant. n is not compile time constant, and hence the program is ill-formed. This is why the program doesn't compile, and why you get the error "expression must have a constant value".

But when I put the same code in any online compiler, it worked fine. How does this happen

This happens because some compilers extend the language and accept ill-formed programs.

how to resolve the issue in Visual Studio 2022.

Don't define array variables without compile time constant size.

I think that the best way to deal with this is dynamic array allocation using vector

You think correctly. Use a vector.

CodePudding user response:

In the C99 version of the C standard variable-length arrays are allowed, No version of C allows them; When you said online compiler did you mean ideone.com? ideone as I know uses gcc of Cygwin, there C (gcc 8.3) as well as C 14 (gcc 8.3) allows varaiable length array which is non-standard

#include <iostream>
using namespace std;
int main() {
    int n;
    cin>>n;
    int a[n];
    for(int i=0;i<n;i  ){
        a[i]=i*i;
        cout<<a[i]<<endl;
    }
    return 0;
}
  • Related