Default parameters in a function

Mar 6, 2009 at 8:31pm
Hi,

I just wondered whether you should define the default parameter in the function prototype or the actual function declaration:

1
2
3
4
5
6
7
8
int foo(int bar = 0);

...

int foo(int bar)
{
// code
}


OR

1
2
3
4
5
6
7
8
int foo(int bar);

...

int foo(int bar = 0)
{
// code
}


(If I put it in both, I get a compile error from g++)

Also, while I'm here, can you tell me whether I should put variable names in the function prototype or just its type:

1
2
3
int foo(int,int,char*);
// OR
int foo(int num, int x, char* text);


Thanks in advance!
Last edited on Mar 6, 2009 at 8:32pm
Mar 6, 2009 at 8:44pm
I like to see default parameters in header files. That way, when you see a function used such as foo() you can look in the header file to see what overloaded functions are available. The header file is where the interface should be; the user of the class/function would want to know the default parameters up front.
Mar 6, 2009 at 8:47pm
For the variable names, I also like them in the header file...rather than adding block comments that explain functions, sometimes aptly named parameters can provide enough insight.
Last edited on Mar 6, 2009 at 8:47pm
Mar 6, 2009 at 8:50pm
You have to specify the defaults in the header.
Mar 6, 2009 at 9:01pm
Oh OK then, thanks!
Mar 6, 2009 at 10:11pm
More questions :)

Would this work, or do I have to assign beforehand?

1
2
3
4
5
6
...

if((a=foo.length())==5)    // assign the length of foo to 'a' and compare that to 5 all in one go
    // do stuff

...


If I should've started a new thread then please tell me.
Mar 6, 2009 at 10:23pm
Yes, that should work
Mar 7, 2009 at 7:24pm
OK, thanks.
Topic archived. No new replies allowed.