This is a tinier lesson that's a bit of a continuation from the last one. A variable's scope is where the variable can be "seen" by other parts of the program.
Let's say we have some nested blocks of code such as this:
{
int a;
{
int b;
b = a;
}
a = b; //Error
}
Blocks of code get "nested." Developers usually show this nesting visually by indenting blocks of code like I've done here. Basically, variables can be seen only by the block of code it's declared in and any blocks nested within the block it was declared in. As you can see in my example the block of code that b is declared in can see a because it's nested within the block a was declared in. The line below that block of code produces an error however because b can't be seen by blocks of code "higher" then the block it was declared in.
The reason for this is that when the end of a block of code is reached any declared variables are discarded and forgotten. In the above example the end of the block the b was declared in was reached and therefore b is discared and forgotten. When a then tries to get b's value the program no longer knows what b is.
Next I'll begin on functions, but at this point you should download the free "Visual C++ Express" from http://www.microsoft.com/express/download/. I'm going to begin teaching from hands-on examples rather than keeping this abstract.
0 \comm\e.nts:
Post a Comment