Is it possible to declare multiple static variables with same name in a single C file?

前端 未结 6 1623
眼角桃花
眼角桃花 2020-12-03 08:34

Is it possible to declare multiple static variables of same name in a single C file with different scopes? I wrote a simple programme to check this and in gcc it got compile

6条回答
  •  眼角桃花
    2020-12-03 09:36

    There is a difference between visibility and extent; also, the static keyword has different meanings based on scope.

    Adding the static keyword to the block scope versions of sVar (myPrint::sVar and main::sVar) changes their extent (lifetime), but not their visibility; both are visible within their respective functions only, and will shadow or hide the file scope version within their local scope. It indicates that the variables have static extent, meaning the memory for them is allocated at program start and held until the program terminates (as opposed to automatic or local extent, where their lifetime is limited to the scope in which they are defined).

    Adding the static keyword to the file scope version of sVar doesn't change its extent (file scope variables have static extent by definition), but it does change its visibility with respect to other translation units; the name is not exported to the linker, so it cannot be accessed by name from another translation unit. It is still visible within the current translation unit, which is why myPrint2 can access it.

提交回复
热议问题