简体   繁体   中英

Scope of function parameter name

What is the scope of function parameter names in c++? I've found that this scope is

function prototype scope

But what does function prototype scope mean?

From the C++2011 International Standard

3.3.4 Function prototype scope [basic.scope.proto]

1 In a function declaration, or in any function declarator except the declarator of a function definition (8.4), names of parameters (if supplied) have function prototype scope, which terminates at the end of the nearest enclosing function declarator.

For example,

auto bar(void (*x)(int y)) -> decltype(y);

is illegal since the scope of y ends at the end of void (*x)(int y) (the nearest enclosing function declarator).

On the other hand,

void bar(auto (*x)(int y) -> decltype(y));

is legal.

The text (I'm assuming) you're reffering to is this:

3.3.4 Function prototype scope [basic.scope.proto]

1 In a function declaration, or in any function declarator except the declarator of a function definition (8.4), names of parameters (if supplied) have function prototype scope, which terminates at the end of the nearest enclosing function declarator.

In a function declaration, for example void foo(int x, int y); , the scope of parameter x is, as per 3.3.2 , immediately after its complete declarator (that is, immediately after x ). Its scope ends at the end of the enclosing function declarator, that is the ; that's ending the declaration.

When talking about function definitions, the scope of parameters is block scope (emphasis mine):

3.3.3 Block scope [basic.scope.local]

1 A name declared in a block (6.3) is local to that block; it has block scope . Its potential scope begins at its point of declaration (3.3.2) and ends at the end of its block. A variable declared at block scope is a local variable .

2 The potential scope of a function parameter name (including one appearing in a lambda-declarator ) or of a function-local predefined variable in a function definition (8.4) begins at its point of declaration. If the function has a function-try-block the potential scope of a parameter or of a function-local predefined variable ends at the end of the last associated handler, otherwise it ends at the end of the outermost block of the function definition. A parameter name shall not be redeclared in the outermost block of the function definition nor in the outermost block of any handler associated with a function-try-block .

Basically, it says that the scope of a parameter ends at the closing brace of the definition.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM