I have been reading the C++ primer 5th edition. In the third paragraph of Function Parameter List of Chapter 6.1 . It writes "Moreover, local variables at the outermost scope of the function may not use the same name as any parameter". What does it mean?
I am not native English speaker. I don't understand the actual meanings of "outermost scope" of the function.
Scope of a variable denotes span of a variable. The scope of a local variable is within that method i.e. when we create a variable with in a method, it cannot be accessed outside that method.
Local variables do not exist outside the block in which they are declared, i.e. they can not be accessed or used outside that block. Declaring local variables: Local variables are declared inside a block.
In computer science, a local variable is a variable that is given local scope. A local variable reference in the function or block in which it is declared overrides the same variable name in the larger scope.
It is usually not a good programming practice to give different variables the same names. If a global and a local variable with the same name are in scope, which means accessible, at the same time, your code can access only the local variable.
The outermost scope of the function is the block that defines the function's body. You can put other (inner) blocks inside that, and declare variables in those which are local to that block. Variables in inner blocks can have the same name as those in an outer block, or the function parameters; they hide the names in the outer scope. Variables in the outer block can't have the same name as a function parameter.
To demonstrate:
void f(int a) // function has a parameter
{ // beginning of function scope
int b; // OK: local variable
{ // beginning of inner block
int a; // OK: hides parameter
int b; // OK: hides outer variable
} // end of inner block
int a; // Error: can't have same name as parameter
}
It means you can't do things like this:
void foo (int x)
{
int x = 4; //in the outermost scope, invalid
}
You can, however, do this:
void foo (int x)
{
{ //this introduces a new scope
int x = 4; //not in the outermost scope, valid
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With