0

I have been using codeblocks for c++ and it has always let me to do this:

#include <iostream>
using namespace std;
int main()
{
    int n; 
    cin >> n; 
    int v[n];
 }

but now when I put this code into visual studio its giving me this error:

expression must have a constant value -- the value of variable "n" (declared at line 7) cannot be used as a constant.

Any idea on how I can fix this, I would really like to use visual studio instead of codeblocks.

Thanks!

David
  • 1
  • 2
  • 3
    VLAs are not part of the C++ standard. They are a gcc extension. Use [`std::vector`](https://en.cppreference.com/w/cpp/container/vector) – bolov Oct 31 '20 at 14:35
  • 1
    Your code is not portable C++ unfortunately. `std::vector v(n);` is virtually a drop-in replacement. Even better, you can use `v.at(i)` for element access rather than `v[i]` (you have a choice). The former performs bounds checks at runtime. – Bathsheba Oct 31 '20 at 14:37
  • 1
    @Bathsheba -- use `v[i]` in contexts where you know that `i` is a valid index. For example, `for (int i = 0; i < v.size(); ++i) ...`. `v.at(i)` is useful when you've lost control of the values that you're dealing with. Which is to say, it's usually an attempt at coding around a design error. – Pete Becker Oct 31 '20 at 16:44
  • @PeteBecker: "use v[i] in contexts where you know that i is a valid index". I think we'll need to disagree on that one. Nobody I'm sure intentionally writes code that accesses out of bounds elements. But if I had a dollar every time I'd seen a "vector out of range" exception, I'd be a lot richer than I am. This is why I've banned the use of `std::vector[]` unless performance profilers identify its use as a bottleneck. – Bathsheba Oct 31 '20 at 19:41

0 Answers0