C Variable Length Arrays storage duration

前端 未结 2 812
陌清茗
陌清茗 2021-02-20 04:01

On this site there is the following paragraph (emphasis mine):

  • automatic storage duration. The storage is allocated when the block in which the ob
2条回答
  •  旧巷少年郎
    2021-02-20 04:50

    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:

    int f(int n) {
        // i is allocated here, _before_ the beginning of its scope
        label: // if control returns here via the goto below, vla is _de_allocated
               // at this point
        printf("n is %d", n);
    
        int vla[n]; // vla is (re)allocated here, at the beginning of its scope
        int i;
        int sum;
    
        for (i = 0; i < n; i++) {
            vla[i] = rand();
            sum += vla[i];
        }
    
        if (sum < SOME_THRESHOLD) goto label; 
    
        return sum;  // vla and i are both deallocated when control exits the block
    }
    

    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.

提交回复
热议问题