Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What does "local variables at the outermost scope of the function may not use the same name as any parameter" mean?

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.

like image 710
LiuHao Avatar asked May 08 '15 13:05

LiuHao


People also ask

What is the meaning of scope What is the scope of a local variable?

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.

Can a local variable be used outside its scope?

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.

What is a local variable What is the scope of a local variable?

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.

Can local variables have the same name?

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.


2 Answers

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
}
like image 137
Mike Seymour Avatar answered Oct 25 '22 06:10

Mike Seymour


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
    }
}
like image 39
TartanLlama Avatar answered Oct 25 '22 04:10

TartanLlama