Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why can't I access a default argument in its initializer in gcc?

This compiles in clang but not in gcc:

void f(int x = decltype(x){});

The error in gcc says that x was not declared in this scope but according to 3.3.2/1 the variable x should be in scope:

The point of declaration for a name is immediately after its complete declarator (Clause 8) and before its initializer (if any), except as noted below. [Example:

int x = 12;
{ int x = x; }

Here the second x is initialized with its own (indeterminate) value. — end example ]

So is clang correct? Should x be accessible in its own initializer?

PS: int x = x as a parameter fails in both compilers but I don't know why.

like image 889
template boy Avatar asked Oct 30 '14 16:10

template boy


People also ask

Can we use default arguments in C?

Default arguments are only allowed in the parameter lists of function declarations and lambda-expressions, (since C++11) and are not allowed in the declarations of pointers to functions, references to functions, or in typedef declarations.

Which are the rules for default arguments?

A default argument is a value in the function declaration automatically assigned by the compiler if the calling function does not pass any value to that argument. The values passed in the default arguments are not constant. These values can be overwritten if the value is passed to the function.

What are the rules of default argument in C++?

Default Arguments in C++ A default argument is a value provided in a function declaration that is automatically assigned by the compiler if the calling function doesn't provide a value for the argument. In case any value is passed, the default value is overridden.

Where can the default arguments be placed by the user?

Explanation: In function parameters the default arguments should always be the rightmost parameters.


1 Answers

GCC is correct; that's not valid.

C++11 8.3.6/9 [dcl.fct.default] parameters of a function shall not be used in a default argument, even if they are not evaluated.

like image 169
Mike Seymour Avatar answered Sep 29 '22 07:09

Mike Seymour