I've noticed that some languages like C, C++, Java, Perl, and .NET Visual Basic have "block" scoping which means that a variable will only be defined within the specific code block it was declared in.
For example (C++):
if (true) {
int x = 1;
}
std::cout << x << std::endl;
This code will fail to compile since x
is only visible within the block scope created by the if
statement.
error: 'x' was not declared in this scope
But languages like VBA, Python, and Javascript have "function based" scoping which means that the only time a new scope is created is when a new function is defined.
For example (VBA):
If True Then
Dim x As Integer
x = 1
End If
MsgBox(x)
This code runs successfully and the value of x
is visible outside of the if
statement.
This type of scoping seems rather confusing to me because visually it looks like x
should "belong" to the if
statement.
So this raises the question: Are there any advantages other than just look and feel... like performance advantages/compile speed advantages/etc... for a language to be "function" scoped rather than "block" scoped?