Caution! That variable you’re accessing might not be what you think it is. Why? Because the scope of a variable defines where in a program it can be seen and modified. Understanding scope is fundamental to good program design, preventing bugs and allowing multiple programmers to work together without accidentally trampling on each other’s data.
💻 Local vs. Global Scope
The two most common types of scope are local and global.
- A local variable exists only within the function where it is created. It is invisible to the rest of the program.
- A global variable is declared outside of any function and is accessible from anywhere in the code.
Consider this Python example:
x = 1
def myfunc():
x = 10
print(x) # This will print 10
myfunc()
print(x) # This will print 1
Inside myfunc()
, a new local variable `x` is created, which shadows the global variable. The global `x` remains unchanged. To modify a global variable from within a function, you must explicitly use the global
keyword: global x
.
💻 The `static` Keyword in C
In languages like C, you can give a local variable a special property with the static
keyword. A regular local variable is destroyed when its function finishes. A static local variable, however, preserves its value between function calls.
void myfunc() {
static int x = 0;
x = x + 1;
printf("x is %d\n", x);
}
If you call this `myfunc()` three times, it will print “x is 1”, “x is 2”, and “x is 3”. The variable `x` is initialized to 0 only the first time. On subsequent calls, it retains its previous value. This is a powerful way to maintain state within a function without using global variables.
More Topics
- Python Project Guide: NumPy & SciPy: For Science!
- Python Project Guide: Times, Dates & Numbers
- Python Project Guide: Making Scripts
- Python Project Guide: Build an FTP Client & Server
- Python Project Guide: Using Functions in Python 3
- Python Project Guide: How to Get Started with Python 3
- Coding Concepts Explained: Avoid Common Coding Mistakes