Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Default Parameter-Can't skip the first one? 1

Status
Not open for further replies.

ironyx

Technical User
Nov 13, 2001
134
US
When you have default parameters in a function, you can't skip the first one without an error. You can however skip the others. Does anyone know why? I gave a short baby program to look at and move stuff around to see what I mean... If anyone knows I would appreciate the knowledge!
Thanks a bunch.

ex:
//Function Prototype
int volume(int length, int width = 5, int height = 2);

//Main Function
int main()
{
//Define Function Arguments
int l = 10;
int w = 15;
int h = 12;

//Function Calls
cout << &quot;The volume is: &quot; << volume(l,w,h)

//return
return 0;
}//End main()
//Function Implementation
int volume(int length, int width, int height)
{
cout << &quot;The parameters are: &quot; << length << &quot; , &quot; << width << &quot; , &quot; << height << endl;
return length * width * height;
}//End volume()
 
for the function
int volume(int length, int width = 5, int height = 2);

you cant skip the first argument because it does not have a predefined value. Think of that function as 3 funcitons all in one

volume(1);// = volume(1,5,2)
volume(1,2); // = volume(1,2,2);
volume(1,2,3);// = volume(1,2,3);

if you want to skip the first argument as well you have to do

int volume(int length = 1, int width = 5, int height = 2);


Matt
 
okay. I got it backwards. If you skip the first one, it allows you to run program but you can't call for it in a function. The program will still compile. If you have the first parameter however and you skip the 2nd or 3rd one, it has an error that stops the compiler saying you are missing the 2nd or 3rd parameter. Is this because it reads from left to right? I can see the precedence of the first parameter so there must be a second and third. Why not the other way though? It lets you skip the first but then lets you have a second and third? Sorry for the confusion. Which really is my confusion.
Thanks,
Va.
 
All parameters with default values must be to the right of any parameters without default values - that is a language requirement. I think that is what you're having a problem with, but let me know if I misread.
 
Okay. That is great. To know it is just a rule of the language. We were in class trying to figure it out and so I thought I would go to outside sources, as we came up clueless. Thanks!!!
-Va.
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top