Default arguments in c++ [closed]
void volume(int l=10, int w=10, int h=10);
int main()
{
clrscr();
volume(); //equivalent to volume(10,10,10)
v开发者_JAVA技巧olume(5); //equivalent to volume(5,10,10)
volume(8,6); //equivalent to volume(8,6,10)
volume(6,7,8);
getch();
return 0;
}
void volume(int l, int w, int h)
{
cout<<"volume = "<<l*w*h<<endl;
}
so now my question is that we are using pass by value then why the value assign when we call the method with empty parameter and the value assignd to the variable got the place. and when we pass other value it does not generate any error.
Because the language is designed to work like that!
Or are you asking how the compiler makes it work?
The standard does not specify how it should work just that it should.
But potentially one solution would be to generate four methods behind the scenes:
void volume()
{
volume(10, 10, 10);
}
void volume(int l)
{
volume(l, 10, 10);
}
void volume(int l, int w)
{
volume(l, w, 10);
}
void volume(int l, int w, int h)
{
cout<<"volume = "<<l*w*h<<endl;
}
Or the compiler could inject tha parameters at the call site:
// source
volume(5);
// Compiler actually transforms the source (internally) and compiles:
volume(5, 10, 10);
The syntax used here:
void volume(int l=10, int w=10, int h=10);
is a bit of compiler nice-ness to simplify later calls.
The compiler doesn't generate functions with fewer arguments, nor does it insert the arguments into the function itself, it simply uses them when you call the function.
That's also why they only have to be specified once, and when you have header and code files, are best put in the header (where calls can see them and the compiler can react accordingly).
Thus, when you have
void volume(int l=10, int w=10, int h=10);
and call
volume(5, 3);
the compiler sees the defaults, handles them, and calls
volume(5, 3, 10); // 10 from the default
Those assignments in the declaration for volume()
are called default parameters, and they're used if you omit the value for a parameter when calling the function.
It's called default assignment. You are telling the compiler that if no value is provided, use 10.
This is the definition of default arguments.
精彩评论