3.4.3 Scope
3.4.3 Scope
Imagine you have a secret diary. Only you can read and write in it. Your friend also has a secret diary, and only they can read and write in theirs. Your diary is "private" to you, and your friend's diary is "private" to them. You can't just open your friend's diary, even if you know they have one.
In programming, Scope refers to where in your code a variable or function can be accessed or "seen." It defines the "visibility" and "lifetime" of variables. Just like your diary is only visible to you, a variable's scope determines which parts of your program can use that variable.
Key Ideas:
- Local Scope:
- Variables declared inside a function (or a specific block of code) have local scope.
- This means they can only be used within that function or block. They are "local" to that area.
- Once the function finishes running, the local variables usually disappear from memory.
Example:
function greet():
message = "Hello!" // 'message' has local scope within 'greet'
print(message)
greet()
// print(message) // ERROR! 'message' cannot be seen outside 'greet' function
- Global Scope:
- Variables declared outside of any function (usually at the very top of your program file) have global scope.
- This means they can be accessed and changed from anywhere in your program.
- Global variables stay in memory for the entire time your program is running.
Example:
program_name = "My Awesome App" // 'program_name' has global scope
function display_name():
print(program_name) // Can access global 'program_name'
display_name()
print(program_name) // Can also access global 'program_name' here
- Block Scope (in some languages):
- Some languages (like Java, C++, and modern JavaScript) also have block scope, meaning variables declared inside if statements, for loops, or other curly {} braces can only be used within those specific blocks.
Understanding scope is important because it helps prevent accidental changes to variables and keeps your code organized. It also helps manage memory, as local variables are cleaned up when their function finishes.
Bibliography:
- GeeksforGeeks - Scope Rules in C: https://www.geeksforgeeks.org/scope-rules-in-c/ (Concepts apply broadly)
- W3Schools - JavaScript Scope: https://www.w3schools.com/js/js_scope.asp
- Wikipedia - Scope (computer science): <https://en.wikipedia.org/wiki/Scope_(computer_programming)>