0

I was trying to make an array of class, but Visual Studio is showing an error Compiler Error C2131 which means "An expression declared as const or constexpr didn't evaluate to a constant at compile time. The compiler must be able to determine the value of the expression at the point it's used."

#include <iostream>
using namespace std;

class instructor
{
public:
    string name;
};

int main(void)
{
    const int num=0;
    cout << "Enter the number of students: ";
    cin >> num;

    instructor student[num];

    return 0;
}

This being the error shown

Error   C2131   expression did not evaluate to a constant
Error (active)  E0028   expression must have a constant value

image for the version of c++

What could be the possible fix for this, rather than dynamic allocation?

NOTE:- But the same code is allowed in GCC code-blocks.

  • 2
    dynamic allocation is the answer, however you can encapsulate that by using a `std::vector` as your "array". – NathanOliver Oct 06 '21 at 13:38
  • Whoever told you that variable-length arrays is a feature of C++14 wasn't telling the truth. – molbdnilo Oct 06 '21 at 13:41
  • Also, it doesn't matter if you are using C++14, 17, or 20, or any version below 14. Arrays must be declared using a compile-time expression denoting the number of entries. If you were using g++ before using Visual C++, then g++ fooled you into thinking you can declare arrays like this. – PaulMcKenzie Oct 06 '21 at 13:41
  • https://stackoverflow.com/questions/1887097/why-arent-variable-length-arrays-part-of-the-c-standard, https://stackoverflow.com/questions/62035501/why-is-this-code-considered-a-vla-even-though-it-uses-an-int, https://stackoverflow.com/questions/20303820/creation-of-dynamic-array-of-dynamic-objects-in-c/20304088 – Nick is tired Oct 06 '21 at 13:42
  • @NathanOliver Or indeed an `std::array` rather than a C-style array – Nick is tired Oct 06 '21 at 13:44
  • @Nick Not when the OP wants to use a size taken from the user. – NathanOliver Oct 06 '21 at 13:44
  • @NathanOliver Huh, TIL, apparently there's an extension for it (`dynarray`). Always forget that `std::array` size is a template parameter :facepalm: – Nick is tired Oct 06 '21 at 13:46
  • There is no `dynarray` in standard C++. – PaulMcKenzie Oct 06 '21 at 13:47
  • @PaulMcKenzie Well I did say "extension" :p – Nick is tired Oct 06 '21 at 13:48
  • [This program does not result in the error you have posted](https://godbolt.org/z/qjGW97vTn). – n. m. could be an AI Oct 06 '21 at 14:47

0 Answers0