Variable scope and duration

A variable scope is a area where the variable is accessible while its duration is a time when it exists.

Variable scopes in C++: local (block) scope, file scope (static keyword for only one file using, and extern keyword for multiple files exploit)

Variable duration in C++: dynamic, static and automatic.

Concluding table:

Type Example Scope Duration Linkage Notes
Local variable int x; Block scope Automatic duration No linkage
Static local variable static int x; Block scope Static duration No linkage
Dynamic variable int *x = new int; Block scope Dynamic duration No linkage
Function parameter void foo(int x) Block scope Automatic duration No linkage
Non-const global variable int g_x; File scope Static duration External linkage Initialized or uninitialized
Static global variable static int g_x; File scope Static duration Internal linkage Initialized or uninitialized
Const global variable const int g_x(1); File scope Static duration Internal linkage
Extern const global variable extern const int g_x(1); File scope Static duration External linkage
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s