visual studio error contsant

How to solve this error

1
2
3
4
5
6
7
8
9
# include <iostream>
using namespace std;
int main()
{
    int n=20;
    int arr[n];      //error n must be constant

return 0;
}
As it says n must be constant at compile time, better to use a std::vector instead:

http://www.cplusplus.com/reference/vector/vector/vector/
Hello zain ahmad.

As TheIdeasMan said a vector would be a better choice, but to use what you have if that is what you need:
1
2
3
4
5
6
7
8
9
10
11
# include <iostream>

using namespace std;

int main()
{
    constexpr int N{ 20 };  // <--- The {}s do the same as "= 20"
    int arr[N];      //error n must be constant

return 0;
}

The capital letter "N" helps to let you know it is defined as a constant. And this is the way it is done most often.

Have a look at http://www.cplusplus.com/doc/tutorial/constants/#const it is short, but a place to start.

I did not find anything in the tutorials on "vectors", but a google search on "c++ vector" should produce something.

Hope that helps,

Andy
Topic archived. No new replies allowed.