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.
Am guessing you have usingnamespace 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 usingnamespace std; is bad also.
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 usingnamespace std;.
I'm compiling with MinGW.
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.