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

前端 未结 6 1619
眼角桃花
眼角桃花 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:28

    Both function will create different stacks, so static part also will be different .Therefore it is possible.

    0 讨论(0)
  • 2020-12-03 09:29

    Your first sVar is global to file, second one is local to the function myPrint() and third one is local to main()

    Function level static variables are not accessible outside the function - they just retain their values on subsequent calls. I assume you've already noted this when you ran your code.

    0 讨论(0)
  • 2020-12-03 09:33

    A function-local static variable is something different than a global static variable.
    Since there can be as many function-local statics with the same name as you like (provided they are all in different scopes), the compiler might have to change their names internally (incorporating the function's name or the line number or whatever), so that the linker can tell them apart.

    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-03 09:37

    Block scoping. Read K & R.

    0 讨论(0)
  • 2020-12-03 09:37

    The static keyword has different meanings when it's global and local, the first sVar is just a global variable unavailable to other translation units. And static variables sVar in myPrint() and main() are in different scopes, so they are different variables. In the body of myPrint() sVar refers to the local static (hiding global sVar), in myPrint2() it refers to the global (it's not hidden by anything local), and in main() it refers to the local static sVar, which again hides the global since the moment it was declared.

    0 讨论(0)
提交回复
热议问题