Search code examples
c++arraysintegerconstants

C++ Creating 2D array with nonconstant size,


I have been using Codeblocks and my code was fine. When I switched to Visual Studio I got an error that says : "expression must have constant value"

int board[n][m];

Solution

  • In contrast to in C there is no variable length array (VLA) in C++ standard, i.e. it is implementation/evnvironemt depending whether you can use them with a compiler or not.
    You got lucky in CodeBlocks and unlucky in Visual Studio.
    Both will allow you to use containers in C++ (e.g. std::vector), which is the recommended way of achieving what you need in C++.

    According to OPs comment, teacher explicitly wanted an array used.
    Most likely what the mean is the container class std::array, see https://en.cppreference.com/w/cpp/container/array .