Is the default argument in the middle of the parameter list?

I saw in our code a function declaration that looked like this

void error(char const *msg, bool showKind = true, bool exit); 

At first I thought it was a mistake, because you cannot have default arguments in the middle of functions, but the compiler accepted this expression. Has anyone seen this before? I am using GCC4.5. Is this a GCC extension?

Strange if I take this in a separate file and try to compile, GCC rejects it. I double-checked everything, including the compiler options used.

+49
c ++ default-arguments
Apr 12 2018-11-11T00:
source share
2 answers

This code will work if in the very first declaration of the function the last parameter has a default value, something like the following:

 //declaration void error(char const *msg, bool showKind, bool exit = false); 

And then in the same scope, you can provide default values ​​for the other arguments (on the right side) in a later declaration:

 void error(char const *msg, bool showKind = true, bool exit); //okay //void error(char const *msg = 0 , bool showKind, bool exit); // error 

which can be called like:

 error("some error messsage"); error("some error messsage", false); error("some error messsage", false, true); 

Online Demo: http://ideone.com/aFpUn

Please note that if you specify a default value for the first parameter (left), without specifying a default value for the second, it will not compile (as expected): http://ideone.com/5hj46




Β§8.3.6 / 4 states:

For non-template functions, by default arguments can be added later function declarations in the same scope.

An example from the standard itself:

 void f(int, int); void f(int, int = 7); 

The second ad adds a default value!

Also see Β§8.3.6 / 6.

+54
Apr 12 2018-11-11T00:
source share

The answer may be in 8.3.6:

8.3.6 Default Arguments

6 With the exception of the member functions of the template class, the default arguments in the definition of a member function that appears outside the class definition are added to the set of default arguments provided by the declaration of the member function in the class definition. By default, the arguments for the member function of the class template must be specified on the initial declaration of the member of the function inside the class template. [Example:

 class C { void f(int i = 3); void g(int i, int j = 99); }; void C::f(int i = 3) // error: default argument already { } // specified in class scope void C::g(int i = 88, int j) // in this translation unit, { } // C::g can be called with no argument 

-end example]

After reading this, I found that MSVC10 accepted the following with disabled compiler extensions:

 void error(char const* msg, bool showKind, bool exit= false); void error(char const* msg, bool showKind = false, bool exit) { msg; showKind; exit; } int main() { error("hello"); } 
+7
Apr 12 '11 at 3:50 a.m.
source share



All Articles