On this site there is the following paragraph (emphasis mine):
- automatic storage duration. The storage is allocated when the block in which the object was declared is entered and deallocated when it is exited by any means (goto, return, reaching the end). One exception is the VLAs; their storage is allocated when the declaration is executed, not on block entry, and deallocated when the declaration goes out of scope, not than when the block is exited (since C99). If the block is entered recursively, a new allocation is performed for every recursion level. All function parameters and non-static block-scope objects have this storage duration, as well as compound literals used at block scope.
What is the difference between a declaration going out of scope and a block being exited? Can you provide an example?
The scope of a block-scope identifier starts at its declaration and extends to the end of the innermost enclosing block. This applies to identifiers of every kind, not just those of VLAs. It is possible for control to leave the scope of an identifier without exiting the innermost block containing it by transferring to a point preceding the identifier's declaration. The most obvious way to accomplish that would be via a
goto
statement:The difference in when a VLA is deallocated vs. when an ordinary automatic object is deallocated mirrors the difference between when the two types of objects are allocated. VLA's live only within the scope of their identifiers.
From the N1570 draft of the C11 specification §6.2.4/7
The specification then adds this helpful note:
So the VLA is de-allocated when the execution goes outside the scope of the VLA, which includes the section in the same block before the declaration of the VLA.
Jumping to a point prior to the declaration can be done with a
goto
statement. For example:In this code, the block is not exited when the
goto
is executed. However, the value ofn
changes, so a newarray
needs to be allocated. That's the horribly convoluted situation that the specification is trying to support.