Cpp plus 1
Cpp plus 1

Reputation: 1010

C difference between compilation of static local variable and static global variable

I know what the difference between these types of variables is, but I'm wondering if making a static variable local actually affects, or can affect the compiler's code-generation in any way.

Upvotes: 0

Views: 139

Answers (2)

lifecrisis
lifecrisis

Reputation: 366

First of all, static external variables (i.e., static variables outside of the scope of any function) are restricted in scope to their translation unit. This is different from a .c file. Basically, a translation unit is the .c file after all preprocessing has completed and every #include file has been added.

A static local variable is different from a static external variable in that it can only be referenced from within the function in which it was declared. It is also notably different from a normal local variable in that it retains its value across function calls (ask me for a snippet to demonstrate, if you're interested).

Does this clarify the difference in your mind?

Upvotes: 1

AnT stands with Russia
AnT stands with Russia

Reputation: 320481

Static variables declared at file scope have the same properties as static variables declared locally (aside from their scope, i.e. visibility region of the identifier). Both kinds have the same storage duration. Both kinds are initialized before program's startup.

There's no reason to expect them to behave differently in terms of code generation.

As a side note: static variables cannot be declared locally in inline definitions of functions, but it is not related to code generation.

Upvotes: 2

Related Questions