A scope or block scope is a visiblity and validiity construct of C and languages with similar syntax such as C++, Java, etc.
Names, e.g. variables, declared in a scope are usually only visible within the scope and nested scopes, not outside, i.e. not in the parent scope or sibling scopes.
Languages such as C and C++, which allow data on the stack, destroy such data when the variable's scope ends.
int main()
{
// inside scope of main()
int a;
a = 3; // valid
{
int b;
// inside a nested scope
a = 4; // valid
b= 4; // valid
}
a = 5; // valid;
b = 5; // will not compile, b only visible/valid in nested scope
}
int main()
{
// inside scope of main()
int a;
a = 3; // valid
{
int b;
// inside a nested scope
a = 4; // valid
b= 4; // valid
}
a = 5; // valid;
b = 5; // will not compile, b only visible/valid in nested scope
}
To copy to clipboard, switch view to plain text mode
In C++, an object such as std::vector is destroyed (its destructor is invoked) when the scope it lives in ends.
int main()
{
vector<int> a;
{
vector<int> b;
}// b is destroyed
}// a is destroyed
int main()
{
vector<int> a;
{
vector<int> b;
}// b is destroyed
}// a is destroyed
To copy to clipboard, switch view to plain text mode
Cheers,
_
Bookmarks