1. What Is a Variable?
A variable is the basic unit in a program used to reference or store data; its associated value can be accessed through its name.
For example:
age = 25
name = "Alice"
price = 19.99
Here three variables are defined:
age: associated with the integer value25.name: associated with the string value"Alice".price: associated with the floating-point value19.99.
A variable is usually made up of the following elements:
| Element | Meaning |
|---|---|
| Name | The name used to identify the variable |
| Value | The data the variable is currently associated with |
| Type | Describes the type of the data and the rules for operating on it |
| Storage Location | The location corresponding to the data or object reference at runtime |
| Scope | The range of code in which the variable can be accessed |
| Lifetime | The period during which the variable or its storage entity exists |
The core role of a variable is to let a program save and manipulate data and maintain state during execution.
1.1 Basic Variable Operations
Variables typically involve the following operations:
Declaration
Declare a variable so that its name has meaning within a specified scope.
int age;
Initialization
The variable receives an initial value for the first time.
int age = 25;
Assignment
Assign a value to a variable, or change the value the variable is currently associated with.
age = 30;
Read
Obtain the value the variable is currently associated with.
System.out.println(age);
Update
Compute a new value from the current value, then assign it back to the variable.
age = age + 1;
Variable operations can be abstracted as:
flowchart TB
A["Declare variable"] --> B["Initialize variable"]
B --> C["Read variable"]
C --> D["Perform computation"]
D --> E["Update variable value"]
E --> C
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style C fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style D fill:#FFF5DE,stroke:#E8D29A,color:#334155
style E fill:#E5F4EC,stroke:#A3CBB5,color:#334155
linkStyle default stroke:#A3B8AC,stroke-width:1.5px
Note that not all languages require explicit declaration and initialization. Python, for example, can establish a binding between a variable name and an object directly through assignment.
2. The Essence of Variables: Names, Values, and Memory
To understand variables, the most important thing is to distinguish between the variable name, the variable value, and the memory storage location.
In different programming languages, the underlying implementation of variables is not entirely the same.
2.1 Variables Do Not Necessarily Store Data Directly
In the C language:
int age = 25;
In a typical implementation, age corresponds to a block of memory capable of storing an integer, and the integer value 25 is stored in it.
This can be simplified as:
Variable name: age
Storage location: some memory address
Stored content: 25
In Python, however:
age = 25
A more accurate understanding is:
25is an integer object.ageis a name.- The name
ageis bound to the integer object.
A Python variable is not like a local integer variable in C, which directly represents a fixed-type block of numeric storage.
Therefore, the underlying semantics of variables can differ greatly between languages.
2.2 A Memory Illustration of Variables
Taking an ordinary local integer variable in C as an example:
int age = 25;
It can be understood with the following illustration:
flowchart LR
A["Variable name age"] --> B["Memory location"]
B --> C["Stored value 25"]
C --> D["Integer type int"]
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style C fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style D fill:#FFF5DE,stroke:#E8D29A,color:#334155
linkStyle default stroke:#A3B8AC,stroke-width:1.5px
This is a conceptual illustration and does not mean that variables in all languages use this direct storage model.
2.3 Variable Names and Variable Values Are Not the Same Thing
Observe the following code:
a = 10
b = a
a = 20
print(a) # 20
print(b) # 10
When b = a is executed, b obtains the object currently associated with a.
Afterwards, a = 20 binds the name a to another integer object, and does not automatically change the binding of b.
This illustrates an important distinction:
Rebinding a variable name is not the same as modifying the original object.
For mutable objects, this distinction is even more important:
a = [1, 2, 3]
b = a
a.append(4)
print(a) # [1, 2, 3, 4]
print(b) # [1, 2, 3, 4]
Because both a and b are bound to the same list object, in-place modifications to the list can be observed through both names.
3. What Is a Constant?
A constant is a language mechanism used to represent a value that should not be reassigned or changed.
For example:
final double PI = 3.141592653589793;
Here, final is used to declare a constant variable, which cannot be assigned again after initialization.
Constants are mainly used to express:
- Mathematical constants
- Configuration parameters
- Fixed business rules
- System limits
- Protocol definitions
- Program data that should not be modified
For example:
MAX_RETRY = 3
DEFAULT_TIMEOUT = 30
API_VERSION = "v1"
Python uses an uppercase naming convention to indicate constant intent, but the language itself does not prevent reassignment.
MAX_RETRY = 3
MAX_RETRY = 5 # Python allows
Therefore, it is necessary to distinguish between:
- Constant constraints actually provided at the language level.
- Constant conventions expressed only through naming conventions.
3.1 Main Characteristics of Constants
| Feature | Description |
|---|---|
| Fixedness | Usually cannot be reassigned |
| Readability | Expresses fixed meaning through names |
| Maintainability | Adjust centrally when modifying configuration |
| Safety | Reduces accidental modification |
| Reusability | Multiple code locations can reference the same constant |
3.2 Constants and Literals
Constants and literals are easily confused.
A literal is a fixed value that appears directly in the source code.
For example:
age = 25
name = "Alice"
enabled = True
Among them:
25is an integer literal."Alice"is a string literal.Trueis a Boolean literal.
A constant, however, is usually a named entity with a fixed value.
For example:
MAX_USERS = 100
Here:
100is a literal.MAX_USERSis a constant expressed through a naming convention.
The relationship between the two can be understood as:
flowchart TB
A["Fixed Value"] --> B["Literal"]
A --> C["Named Constant"]
B --> D["Written directly in code"]
C --> E["Referenced by name"]
E --> F["Associated fixed value"]
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style C fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style D fill:#E8EDF2,stroke:#B8C3CE,color:#334155
style E fill:#FFF5DE,stroke:#E8D29A,color:#334155
style F fill:#E5F4EC,stroke:#A3CBB5,color:#334155
linkStyle default stroke:#A3B8AC,stroke-width:1.5px
A literal describes how a value is represented in source code; a constant describes how a value is named and constrained.
IV. Differences Between Variables and Constants
Both variables and constants are used to express data in a program, but they impose different constraints on whether a value can change.
| Comparison Dimension | Variable | Constant |
|---|---|---|
| English | Variable | Constant |
| Assignment | Reassignment is usually allowed | Reassignment is usually restricted |
| Value change | Can change | Usually cannot change |
| Use cases | Runtime state, temporary data, computed results | Fixed configuration, rules, parameters |
| Maintainability | Requires attention to state changes | Helps manage fixed values in a unified way |
| Typical declarations | let, var, ordinary variable declarations |
const, final, const |
For example:
int score = 80;
score = 90;
final int MAX_SCORE = 100;
score can be updated, whereas MAX_SCORE cannot be assigned again.
But note:
A constant does not necessarily mean that the object it references is completely unmodifiable in memory.
This involves an important distinction between constants and immutable objects.
V. Constants and Immutable Objects
A constant and an immutable object are not the same concept.
This is a place where mistakes are very easy to make in real-world development.
5.1 A Constant Constrains Variable Binding or Assignment
For example, in Java:
final List<String> names = new ArrayList<>();
names.add("Alice");
names.add("Bob");
// names = new ArrayList<>(); // compile error
Here:
namesis afinalreference variable.namescannot be reassigned to point to another list object.- The list object itself can still be modified.
In other words, final constrains the reference variable so that it cannot be reassigned; it does not automatically make the list contents immutable.
5.2 An Immutable Object Constrains Object State
Once an immutable object is created, its internal state cannot change.
For example, in Python:
name = "Alice"
name = "Bob"
The string object itself is immutable.
The second assignment does not modify the original string; instead, it binds name to another string object.
Now consider a tuple:
user = (1001, "Alice")
The tuple itself cannot be modified, but if the tuple contains mutable objects, the internal state of those objects may still change:
data = ([1, 2], "Alice")
data[0].append(3)
print(data) # ([1, 2, 3], 'Alice')
The tuple structure is not modified, but the list inside it has changed.
5.3 Differences Between Constants and Immutable Objects
| Comparison Dimension | Constant Constraint | Immutable Object |
|---|---|---|
| What is constrained | Name, variable, or binding | The object's own state |
| Whether reassignment is allowed | Usually not allowed | Depends on the reference variable |
| Whether internal state can be modified | Not necessarily | Not allowed |
| Main purpose | Restrict reassignment | Ensure object state stability |
This can be understood as follows:
flowchart TB
A["Data immutability"] --> B["Assignment immutability"]
A --> C["Object immutability"]
B --> D["Limit variable reassignment"]
C --> E["Limit changes to object internal state"]
D --> F["Constant mechanism"]
E --> G["Immutable object"]
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style C fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style D fill:#FFF5DE,stroke:#E8D29A,color:#334155
style E fill:#FFF5DE,stroke:#E8D29A,color:#334155
style F fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style G fill:#E5F4EC,stroke:#A3CBB5,color:#334155
linkStyle default stroke:#A3B8AC,stroke-width:1.5px
In concurrent programming, functional programming, and large-scale system design, immutable objects are valuable because they reduce the complexity caused by changes to shared state.
6. Variable Declaration, Definition, and Initialization
Variable declaration, definition, and initialization are three related but distinct concepts.
6.1 Declaration
A declaration tells the compiler or runtime environment that a name has a specific meaning.
For example, in C:
extern int age;
This declares an external integer variable but does not define its storage entity here.
6.2 Definition
A definition typically creates the variable entity and allocates storage according to the applicable language rules.
For example:
int age;
Here, age is both declared and defined.
In C, the distinction between variable declaration and definition has a clear meaning in the language specification.
6.3 Initialization
Initialization is the process by which a variable receives its initial value when it is created.
int age = 25;
This defines the variable and initializes it to 25.
Note that different languages handle uninitialized variables very differently:
- In C, an uninitialized local variable with automatic storage duration has an indeterminate value.
- In Java, instance fields and static fields have default values, while local variables must be explicitly assigned before use.
- In Go, variables receive the zero value of their corresponding type.
- In Python, a name cannot be read directly before it is bound to an object; otherwise, a
NameErroror a related exception is typically raised.
Therefore, the initialization rules of one language cannot be directly applied to other languages.
7. Variable Scope (Scope)
Scope is the range of code in which a variable name can be accessed.
A variable's scope determines where in the program it can be referenced by name.
Common scopes include:
- Global scope
- File or module scope
- Function scope
- Block scope
- Class scope
7.1 Global Scope
Global variables are usually visible across a larger program scope.
For example, in Python:
message = "Hello"
def greet():
print(message)
greet()
message is defined outside the function and can be read inside the function.
However, if you need to rebind a global variable inside a function, you need to use global:
count = 0
def increment():
global count
count += 1
7.2 Local Scope
Local variables are typically defined inside a function and can only be accessed within the corresponding local scope.
def calculate():
result = 100
print(result)
calculate()
# print(result) # NameError
result is valid inside the function and cannot be accessed directly outside it.
7.3 Block Scope
Block scope is usually delimited by a pair of code block boundaries, such as {}.
Java:
public class Main {
public static void main(String[] args) {
if (true) {
int value = 10;
System.out.println(value);
}
// System.out.println(value); // Compile error
}
}
value is only valid inside the if block.
Variables declared in JavaScript with let and const also have block scope.
7.4 Scope Nesting and Variable Shadowing
Variable shadowing can occur when an inner scope defines a variable with the same name as a variable in an outer scope.
For example:
let name = "Global";
function greet() {
let name = "Local";
console.log(name);
}
greet(); // Local
console.log(name); // Global
The name inside the function shadows the outer name.
Variable shadowing is not the same as modifying the outer variable; instead, it uses another binding with the same name in the current scope.
7.5 Scope Diagram
flowchart TB
A["Global Scope"] --> B["Function Scope"]
B --> C["Block Scope"]
A --> D["Other Function Scope"]
C --> E["Block-local Variable"]
B --> F["Function-local Variable"]
A --> G["Global Variable"]
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style C fill:#F3EDFC,stroke:#C4B2E3,color:#334155
style D fill:#E5F4EC,stroke:#A3CBB5,color:#334155
style E fill:#FFF5DE,stroke:#E8D29A,color:#334155
style F fill:#FFF5DE,stroke:#E8D29A,color:#334155
style G fill:#FFF5DE,stroke:#E8D29A,color:#334155
linkStyle default stroke:#A3B8AC,stroke-width:1.5px
This is a conceptual illustration of scope nesting. Scope rules are not completely consistent across languages; for example, JavaScript also involves mechanisms such as lexical scope, closures, and the temporal dead zone.
VIII. Variable Lifetime (Lifetime)
Scope and lifetime are two different concepts.
- Scope concerns: where a variable name can be accessed.
- Lifetime concerns: when a variable or the related storage entity is created and when it is destroyed.
For example:
void test() {
int count = 10;
}
In a typical C implementation, count is a local variable with automatic storage duration, and its lifetime is tied to the execution of the function.
When the function finishes executing, the variable's lifetime ends.
However, one cannot simply assume that all local variables are destroyed when the function returns.
Different languages have different memory management mechanisms:
| Language | Common lifetime management approach |
|---|---|
| C | Automatic storage duration, static storage duration, dynamic allocation |
| C++ | Automatic objects, static objects, dynamic objects, RAII |
| Java | Objects are managed by garbage collection |
| Python | Object lifetime is affected by reference relationships and garbage collection |
| Go | Memory management involves both compiler escape analysis and garbage collection |
| Rust | Ownership, borrowing, and lifetime rules |