public void MyFunction()
{
Int64 MyVariable1 = 0;
Int64 MyVariable2 = 1;
}
As most of us knows, everything inside that function is locally scoped. That means only things inside MyFunction can access MyVariable1 & MyVariable2. Let's expand this.
public void MyFunction()
{
Int64 MyVariable1 = 0;
Int64 MyVariable2 = 1;
Int64 MyVariableChoice = 2;
if(MyVariableChoice)
{
Int64 MyVariable3 = 0;
}
else if(MyVariableChoice)
{
Int64 MyVariable3 = 1;
}
}
As most of us knows, MyVariable3 can only be accessed by statements inside the if(MyVariableChoice)block. Each instance of MyVariable3 is a local variable and memory is allocated for it's creation when the code reaches that block.
For most of us, all this is common sense. Let me rattle that common sense for a few programmers out there. Look at this switch statement:
public void MyFunction()
{
Int64 MyVariable1 = 1;
switch(MyVariable1)
{
case 1:
Int64 MyVariableCase = 1;
PrivateFunction(MyVariableCase);
break;
case 2:
Int64 MyVariableCase = 2;
PrivateFunction(MyVariableCase);
break;
default:
break;
}
}
If you try and compile this, you'll get an error. This is because a switch-case by itself doesn't allow for local variables. To make MyVariableCase a local variable, you need to surround it with a { } block so it looks like this.
Now let's change it a bit. Look at this switch statement:
public void MyFunction()
{
Int64 MyVariable1 = 1;
switch(MyVariable1)
{
case 1:
{
Int64 MyVariableCase = 1;
PrivateFunction(MyVariableCase);
}
break;
case 2:
{
Int64 MyVariableCase = 2;
PrivateFunction(MyVariableCase);
}
break;
default:
break;
}
}
This will compile and MyVariableCase will be defined as local variable. Noticed when I turned the free statements and put them inside a { } block, all the variables are now local. This is allowed by 5.1.7 of the C# Language Specifications v 3.0.
"A local variable is declared by a local-variable-declaration, which may occur in a block, a for-statement, a switch-statement or a using-statement; or by a foreach-statement or a specific-catch-clause for a try-statement." -5.1.7 Introduction
Now, before you go crazy with limiting local scope with blocks, remember, I only demonstrated this with C#. PLEASE read your language specification manual to make sure that your language supports scope by blocks. Highly popular languages such as Javascript DO NOT ALLOW LOCAL VARIABLES BY BLOCKS. Local variables in Javascript is allowed by functions but not blocks. Please don't try the case example above for Javascript. See Douglas Crockford's video on "The Javascript Programming Language" for more details.
0 comments:
Post a Comment