Can the address of a variable with automatic storage duration be taken in its definition?

前端 未结 3 1930
不知归路
不知归路 2021-01-14 17:08

Is it allowed to take the address of an object on the right hand-side of its definition, as happens in foo() below:

typedef struct { char x[100]         


        
3条回答
  •  灰色年华
    2021-01-14 17:23

    6.2.1 Scopes of identifiers

    1. Structure, union, and enumeration tags have scope that begins just after the appearance of the tag in a type specifier that declares the tag. Each enumeration constant has scope that begins just after the appearance of its defining enumerator in an enumerator list. Any other identifier has scope that begins just after the completion of its declarator.

    In

    chars b = make(&b);
    //    ^^
    

    the declarator is b, so it is in scope in its own initializer.

    6.2.4 Storage durations of objects

    1. For such an [automatic] object that does not have a variable length array type, its lifetime extends from entry into the block with which it is associated until execution of that block ends in any way.

    So in

    { // X
      chars b = make(&b);
    }
    

    the lifetime of b starts at X, so by the time the initializer executes, it is both alive and in scope.

    As far as I can tell, this is effectively identical to

    {
      chars b;
      b = make(&b);
    }
    

    There's no reason you couldn't use &b there.

提交回复
热议问题