array size unknown

Hello, I'm new to c++ and compiled languages in general..I made a mistake that did not result in a compile error (or execution error) and I was wondering why. I set the size of an array to a variable that is not known until runtime. Any idea why no error was raised? Thanks!

1
2
  int xyz = func(arg); //return value only known at runtime
  std::string array[xyz]; //no compile error 
If you compiler let you get away with an array size that wasn't a compile time constant, it's not a fully compliant compiler. That happens more than you might like.
Hi,

Might need some more context here.

Am guessing you have using namespace std; (itself a bad idea), so array is really std::array which can have an have an initial variable size. But you would have to #include <array> for that to happen.

Does it produce an error if you name it something else?

So array is a bad name for a variable, and using namespace std; is bad also.

Can we see more code?
so array is really std::array which can have an have an initial variable size.
std::array is under the same constraints with respect to size that native arrays are - that size must be a compile time constant.

OP: http://stackoverflow.com/a/17840435
Sorry, I just used some bogus variable names since mine wouldn't make sense...I can see that my choice of the name "array" was not good...here are the actual names:
1
2
3
4
5
6
7
int csst; //declare elements variable
csst = getdatafromfile(pFile); //get num of elements from file
std::string sst[csst]; //declare array of strings
sst[0]="xyz";
.
.
.


I didn't use using namespace std;.
I'm compiling with MinGW.

Thanks for your response!
Last edited on
I'm compiling with MinGW.

and which compiler options did you specify?
For example: -std=c++11 -Wall -Wextra -pedantic
Chervil, I see what you are getting at...you are correct, I didn't make the compiler very restrictive g++ test.cpp -o test.exe. I guess the execution may have gone ok because of garbage in the csst variable that just happened to allow for the number of elements I needed.

Thanks everyone for your replies!
I guess the execution may have gone ok because of garbage in the csst variable that just happened to allow for the number of elements I needed

I don't think that's it exactly. Variable-length arrays is a non-standard extension provided by the gnu compiler.
https://gcc.gnu.org/onlinedocs/gcc/Variable-Length.html#Variable-Length

With g++ use these options to get an error rather than just a warning:
-std=c++11 -Wall -Wextra -pedantic-errors
Thanks again Chervil...very helpful!
Topic archived. No new replies allowed.