My C++ is very rusty, trying to polish the rust off here !
I thought this code shouldnt compile for C++
int size = 5;
int array;
This seems to compile OK for me in the Arduino IDE and PlatformIO.
Setting an array size at run time is kind of handy and saves me having to struggle with
getting an STL library. Can someone clarify why this compiles without requiring
const int size = 5;
int size = 5;
int array[size];
void setup()
{
}
void loop()
{
}
Does not compile for me in the Arduino IDE
sketch_dec08d:2:15: error: array bound is not an integer constant before ']' token
int array[size];
^
exit status 1
array bound is not an integer constant before ']' token
Idahowalker:
Why does int size have to be a constant; C++ Arrays?
Is this a question?
OP, turn on Compiler Warnings in preferences and the compiler will complain.
When you declare an array, the array size cannot be changed by the program, so it needs to be a const int.
Some C++ compilers allow a non constant array size specifier if the array is automatic. That is, it is defined within a function. Not, however, as a global.
Thanks for the reply 6v6gt, my experiment just confirmed exactly what you stated. It is down to different behaviours between compilers. The sizing of an array is pretty simple and fundamental stuff, I am surprised they arent more consistent.
Variable-length automatic arrays are allowed in ISO C99, and as an extension GCC accepts them in C90 mode and in C++. These arrays are declared like any other automatic arrays, but with a length that is not a constant expression. The storage is allocated at the point of declaration and deallocated when the block scope containing the declaration exits.
The MSVC compiler doesn't support this extension, but GCC does.