2

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?

2
  • 3
    Some compilers may allow variable-length arrays as an "extension", given certain options. They are non-standard and prone to error, and you should not use them, ever. Commented Jun 9, 2022 at 9:19
  • 3
    Use std::vector instead. Commented Jun 9, 2022 at 9:21

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.