There is global scope which means it's in a header, but outside of any namespace or class.
There is file scope, which you can put a variable in a CPP file outside of any namespace, class or function and only that file can interact with it.
There is member scope ( don't know if that is what it's real name is ) where you have a variable in a class, struct or union ( all considered class types ).
Then there is local scope. This can be anything between { and } inside a function.
Code: Select all
void Foo()
{ // begin scope A
// This is one scope
{ // begin scope B
// This would be limiting the scope even further inside the same function
//
}// End scope B
} // End scope A
You'll often see chili use this scoping inside functions to be able to reuse variable names within the same function
Code: Select all
void Foo()
{
const int a = 42;
const int b = 27;
const int c = 118;
{
const int result = a + b;
// Do something with result
}
{
const int result = a + c;
// Do something else with result;
}
}
One reason for doing this is so you can make the result const, which helps optimize your code during compilation. Without it, you'd have two options, have each result be a different name in order to keep them const, or lose the const and rewrite the second result to the result variable.
Another reason might be for multi-threading where you need to lock other threads while the current thread is working on shared data. You don't want to lock for longer then needed, so you might use a scoped guard that when the scope ends, the other threads are allowed to continue their work. Without mechanism, you'd be responsible for locking and unlocking manually, or have to wait for the end of the function which is a waste of time.
There is also something called static scope. One case is if you define a static variable inside a function, it is put in the same place as global memory, but can only be interacted with during that function call.
Code: Select all
void Foo()
{
static int s_val = 42;
}
You can change the value, it is remembered between calls and it doesn't get reinitialized back to 42 each time. It never dies until you end your program.
If you think paging some data from disk into RAM is slow, try paging it into a simian cerebrum over a pair of optical nerves. - gameprogrammingpatterns.com