In C++, understanding how variables and functions behave in terms of scope, duration, and linkage is essential for writing robust and modular code. These three foundational concepts define:
- 🔹 Scope – Where in the code a variable or function is accessible.
- 🔹 Duration (Storage Duration) – How long the variable exists in memory.
- 🔹 Linkage – Whether a variable or function is accessible from other files.
Let's explore each in detail.
1️⃣ Scope – Where You Can Access a Variable or Function
Scope determines the region of the program where a particular identifier, such as a variable or function, is accessible or visible. Once you move out of the scope, you can no longer access that entity.
Below are the different types of scope:
✅ Block Scope (Local Scope):
- Definition: Variables declared inside blocks (e.g.,
{}
within functions, loops, or conditionals) are only accessible within that block. - Visibility: These variables disappear or destroyed, when the block ends.
- They are known as local variables.
Example:
void myFunction() {
int x = 10; // x is only visible inside myFunction
if (true) {
int y = 20; // y is only visible inside this if block
}
// y is no longer accessible here
}
Variables with block scope are local
to the block in which they are declared.
✅ Function Scope:
- Variables declared within a function but outside of any block have function scope.
- They are visible throughout the entire function.
Note: In modern C++, block scope is generally used; function scope is more a legacy term in some contexts.
int globalVar = 20; // globalVar has function scope
int main() {
// globalVar is accessible here
// ...
}
✅ File Scope (Global Scope):
- Variables or functions declared outside of any function (global variables or functions) have file scope.
- They can be accessed throughout the file after declaration.
Example:
// file scope variable
int globalVar = 30;
int main() {
// globalVar is accessible here
// ...
}
✅ Class Scope (C++ only):
- Members of a class in C++ have class scope.
- They can be accessed within the class using objects or methods, and access control is defined by access specifiers (
private
,protected
,public
).
Example:
class MyClass {
private:
int privateVar; // Only accessible within MyClass
public:
void setVar(int val) { privateVar = val; } // Access within class methods
};
2️⃣ Duration (Storage Duration) - How Long a Variable Lives
Storage Duration defines how long a variable stays in memory during program execution. It tells us how long the variable's value is retained.
Below are the different types of duration.
✅ Automatic Duration (Local Variables):
- Applies to: Local variables declared inside a function or block (those with block scope).
- Lifetime: They exist when the block is entered and disappear when the block is exited.
- Default for non-static local variables.
Example:
void myFunction() {
int x = 10; // x is created when the function is called
// x exists while the function runs
} // x is destroyed when the function ends
⚠️ Key Point: Automatically managed by the compiler, variables are created and destroyed automatically as the block or function starts or ends.
✅ Static Duration
- Applies to: Variables with static duration exist for the entire duration of the program, even if they are declared inside a function or block. They are initialized only once and retain their value across function calls.
- Lifetime: Entire program execution
- Initialization: Happens once
- Use the
static
keyword to define such variables.
Example:
void myFunction() {
static int counter = 0; // counter is initialized only once
counter++; // Retains its value across multiple function calls
}
- Key Point: Static variables are created once and live until the program ends, even if they are declared inside a function.
✅ Dynamic Duration
- Applies to: Variables created using
new
ormalloc
- Lifetime: Until explicitly deallocated
- Management: Programmer-controlled
Example:
int* p = new int(10); // p points to a dynamically allocated integer
// use ... p
delete p; // Free the memory manually
⚠️ Key Point: Risk of memory leaks or dangling pointers if mismanaged.
✅ Thread Storage Duration (C++11 and later)
- Variables declared with the
thread_local
keyword have thread storage duration. - Each thread gets its own copy of the variable, and the variable exists as long as the thread does.
Example:
thread_local int threadVar = 0; // Each thread has its own copy of threadVar
3️⃣ Linkage - Accessibility Across Translation Units (Files)
Linkage controls whether an identifier (variable | function) is accessible across different files in a multi-file program.
Below are the different types of Linkages:
✅ No Linkage
- Applies to: local variables inside blocks (e.g., inside a function)
- Accessibility: Not accessible from outside their block.
Example:
void myFunction() {
int x = 10; // x has no linkage, it is local to this function
}
🔐 Key Point: These variables are confined to their scope only.
✅ Internal Linkage
- Applies to: Variables or functions declared as
static
at file scope - Accessibility: Only within the same source file
Example:
static int internalVar = 100; // internalVar is only accessible in this file
🔐 Key Point: Internal linkage restricts access to variables or functions from outside the current file.
Use this for encapsulation within a file/module.
✅ External Linkage
- Applies to: Global variables/functions not marked
static
- Accessibility: Available across multiple source files using
extern
- Use
extern
to refer to them in other files.
Example:
// File1.cpp
int globalVar = 42; // globalVar has external linkage by default
// File2.cpp
extern int globalVar; // references globalVar from File1.cpp
🔑 Key Point: Use
extern
to share variables/functions between files.
Summary Table
Concept | Description | Example Keywords |
---|---|---|
Scope | Region where variable/function is accessible | Local, Global, Class |
Duration | Lifetime of a variable in memory | auto , static , new , thread_local |
Linkage | Accessibility across translation units (files) | static , extern |