Default parameters in a function

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
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.
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
You have to specify the defaults in the header.
Oh OK then, thanks!
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.
Yes, that should work
OK, thanks.
Topic archived. No new replies allowed.