Share via

MS Visual Studio C2131 - expression did not evaluate to a constant - C++

Isaac GM 20 Reputation points
2025-01-07T09:19:04.34+00:00

Hello.

I have a simple code in MS Visual Studio with C++ that aims to enter values ​​into a two-dimensional matrix and display the entered values ​​on the screen.

When I write exactly the same code in DevC++, it works but in MS Visual Studio, it gives the error "C2131 expression did not evaluate to a constant" on the line I marked as LINE 39.

I'm guessing it's an issue with the compiler or C++ standards but I couldn't find a solution for this code.

How can I solve this problem? How can I make the code I wrote work?

Thank you in advance to everyone who takes the time to help.

#include <iostream>
#include <stdio.h>

using namespace std;

int main() {

	int R, C;

	cout << "Enter the value of the row:    "; 	cin >> R;
	cout << "Enter the value of the column: "; 	cin >> C;
	cout << endl;


	int a[R][C];      // >>>>>>>>>>>>>>>> LINE 39, C2131 Error <<<<<<<<<<<<<<<


	for (int i = 0; i < R; i++) {

		for (int j = 0; j < C; j++) {

			cout << i + 1 << ". row, " << j + 1 << ". column: "; cin >> a[i][j];
		}

		cout << endl;
	}

	cout << endl << endl;


	for (int i = 0; i < R; i++) {

		for (int j = 0; j < C; j++) {

			cout << "\t" << a[i][j];
		}

		cout << endl;
	}


	return 0;
}

Developer technologies | C++
Developer technologies | C++

A high-level, general-purpose programming language, created as an extension of the C programming language, that has object-oriented, generic, and functional features in addition to facilities for low-level memory manipulation.

Developer technologies | Visual Studio | Other
Developer technologies | Visual Studio | Other

A family of Microsoft suites of integrated development tools for building applications for Windows, the web, mobile devices and many other platforms. Miscellaneous topics that do not fit into specific categories.

0 comments No comments

Answer accepted by question author

  1. Viorel 126.9K Reputation points
    2025-01-07T10:05:02.0233333+00:00

    You are using a compiler that offers a non-standard additional feature: Variable-Length Arrays.

    In Visual Studio, try an alternative:

    //int a[R][C];      // >>>>>>>>>>>>>>>> LINE 39, C2131 Error <<<<<<<<<<<<<<<
    vector<vector<int>> a( R );
    for( auto& r : a ) r.resize( C );
    

    Also add #include <vector>.

    However, there are other solutions.

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.