Scope of variably sized array-Collection of common programming errors
No, for two separate reasons:
C++: The code isn’t valid C++. Arrays in C++ must have a compile-time constant size.
C: No, because the array only lives until the end of the block in which it was declared, and thus dereferencing x
is undefined behaviour.
From C11, 6.2.4/2:
If an object is referred to outside of its lifetime, the behavior is undefined.
And 6.2.4/7 says that the variable-length array lives from its declaration until the end of its enclosing scope:
For such an object that does have a variable length array type, its lifetime extends from the declaration of the object until execution of the program leaves the scope of the declaration.
Originally posted 2013-11-09 21:08:52.