Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I saw a function declaration in our code that looked as follows

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

I thought first that this is an error because you cannot have default arguments in the middle of functions, but the compiler accepted this declaration. Has anyone seen this before? I'm using GCC4.5. Is this a GCC extension?

The weird thing is, if I take this out in a separate file and try to compile, GCC rejects it. I've double checked everything, including the compiler options used.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
225 views
Welcome To Ask or Share your Answers For Others

1 Answer

That code would work if in the very first declaration of the function, the last parameter has default value, something like this:

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

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

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

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

which can called as:

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

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

Note if you provide default value for the first parameter (from left), without providing default value for the second, it wouldn't compile (as expected) : http://ideone.com/5hj46


§8.3.6/4 says,

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

Example from the Standard itself:

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

The second declaration adds default value!

Also see §8.3.6/6.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...