Intern
What is scope in programming and how does it work?
sobes.tech AI
Answer from AI
Scope defines the accessibility of variables, functions, and other identifiers in different parts of a program. It limits the lifetime and accessibility of these elements.
There are different types of scope:
- Local Scope: Variables declared inside a function. Accessible only within that function.
- Global Scope: Variables declared outside any functions or classes. Accessible from any part of the program.
- Block Scope: Variables declared inside a block of code, such as within
if,for, orwhile. Accessible only within that block (in languages supporting block scope, such as Java, Kotlin, C++).
When accessing an identifier, the programming language searches for it "from the inside out": first in the current scope, then in enclosing scopes, and so on up to the global scope. Once the identifier is found, the search stops.
Example in Kotlin:
var globalVariable = "I am global" // Global scope
fun myFunction() {
var localVariable = "I am local" // Local scope
if (true) {
val blockVariable = "I am block" // Block scope
println(globalVariable) // Access to global
println(localVariable) // Access to local
println(blockVariable) // Access to block
}
// println(blockVariable) // Error: blockVariable is not accessible outside the block
println(globalVariable) // Access to global
println(localVariable) // Access to local
}
fun anotherFunction() {
println(globalVariable) // Access to global
// println(localVariable) // Error: localVariable is not accessible outside myFunction
}