0

Even though my code is running correctly VS Code is highlighting it as an error. This started happening suddenly, until two hours back every thing was fine. I am compiling my code in C++.

void next_greater_element(int a[], int n)
{
    int ans[n];

ans[n] is being highlighted as an error. The error says --

expression must have a constant value -- the value of parameter "n" (declared at line 102) cannot be used as a constantC/C++(28)

Image of the highlighted error

  • 2
    Because a variable length array does not follow the C++ standard. – Wais Kamal Aug 14 '21 at 08:22
  • VSC is right, and your code is wrong. C++ standard doesn't allow this, though some compilers accept it unless told not to. – HolyBlackCat Aug 14 '21 at 08:26
  • I am not trying to declare a variable sized array. If I wanted to a variable sized array I would have used a vector. I was simply declaring an array of size 'n'. The bigger problem is that the code is running perfectly but VS code shows that there is an error. – angry_coder Aug 14 '21 at 08:33
  • 1
    No, `int ans[n];` is a [variable-length array](https://en.wikipedia.org/wiki/Variable-length_array) and illegal in standard C++. `std::vector` is a legal alternative. Unsure if it's possible to make VSC accept this, but IMO it's better to fix your code. – HolyBlackCat Aug 14 '21 at 08:35
  • @HolyBlackCat VSC may be doing the correct thing now by telling me this is an error but it wasn't doing this earlier. Is there any way to make it the way it was before? – angry_coder Aug 14 '21 at 09:40
  • I'm not sure, sorry. – HolyBlackCat Aug 14 '21 at 09:41

0 Answers0