In C++ I tried declaring a global array of some size. I got the error:
array bound is not an integer constant before ‘]’ token
But when I declared an array of the same type in the main()
function it is working fine.
Why is there different behaviour here?
int y=5;
int arr[y]; //When I comment this line it works fine
int main()
{
int x=5;
int arr2[x]; // This line doesn't show any error.
}
Edit: Many are suggesting this question is a duplicate of Getting error "array bound is not an integer constant before ']' token". But that question doesn't answer why there is different behaviour.
main
, it is not legal, it uses VLA extension. – Womanhoodmain
is "accepted" by your compiler: you are using the compiler extension, that allows VLAs to compile, even if they are not supported by C++ standard. – Rheniumy
andx
asconst
? Do you need to modify the value ofy
orx
? Hopefully not, because that raises many questions about how bigarr
andarr2
should be -- especially with repsect to initialization order. (Hint: they should be constants) – Zygote--std=c++17
(or--std=c++11
if it's an older compiler), and compilation will fail. – Correggio// This line doesn't show any error
-- Yes it does. (rextester.com/NXZDT64108) – Brenan