Generally we declare the array in following format:
DataType array_name[SIZE];
SO If I tried creating 0 length array for e.g.
int arr[0]; //Line#1
arr[0] = 5; //Line#2
I do not get any error when above code is executed.In this case is memory allocated for single integer?
Why does the Line#1 not generate any compilation error?
Ideally, it should!
It is not legal code to create an array of size
0on local storage.Ideally, the compiler should issue you an error, probably some compiler extension allows this to compile but as per the standard this is not a valid code.Try compiling with
-pedantic.Reference:
C++03 Standard 8.3.4/1:
Further,
Why does the Line#2 not generate any compilation error?
Because writing beyond the bounds of an allocated array is Undefined Behavior. An Undefined Behavior does not need the compiler to provide you any diagnostic. Note that once the code exhibits an Undefined Behavior literally anything can happen and all bets are off.