Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does VS require constant for array size, and MinGW does not? And is there a way around it?

I have ported some code from Mingw which i wrote using code::blocks, to visual studio and their compiler, it has picked up many errors that my array sizes must be constant! Why does VS need a constant size and mingw does not?

e.g.

const int len = (strlen(szPath)-20);
char szModiPath[len];

the len variable is underlined in red to say that its an error and says "expected constant expression"

The only way i can think to get around this is....

char* szModiPath = new char[len];
delete[] szModiPath;

Will i have to change everything to dynamic or is there another way in VS?

like image 961
Kaije Avatar asked Dec 22 '22 00:12

Kaije


2 Answers

Why does VS need a constant size and mingw does not?

Because Variable Length Arrays are not a part of C++ although MinGW(g++) supports them as extension. Array size has to be a constant expression in C++.

In C++ it is always recommended to use std::vector instead of C-style arrays. :)

like image 68
Prasoon Saurav Avatar answered Feb 28 '23 09:02

Prasoon Saurav


The only way i can think to get around this is....

This is not "the only way". Use STL containers.

#include <string>

....
std::string s;
s.resize(len);

or

#include <vector>

....

std::vector<char> buffer(len);

P.S. Also, I don't think that using hungarian notation in C++ code is a good idea.

like image 34
SigTerm Avatar answered Feb 28 '23 11:02

SigTerm