Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you make a prototype of a function with parameters that have default values?

Tags:

c++

A have a function with a prototype of:

void arryprnt(int[], string, int, string, string);

And a definition of:

void arryprnt(int[] a, string intro, int len, string sep=", ", string end=".") {
// stuff
}

And I'm calling it like this:

arryprnt(jimmy, "PSEUDOJIMMY: ", 15);

...When I make that call to arryprnt, I get a compiler error saying that I've used too few arguments, based off what the prototype says. "Okay," I'm thinking, "The compiler doesn't know that some of arryprnt's parameters have default values. I'll just copy the parameters from the definition into the prototype." And I did, however, I got a compiler error telling me that I was calling arryprnt with too many arguments! I could just explicitly specify all the arguments, but is there any way to call it without specifying all the arguments?

like image 371
Xonara Avatar asked May 31 '09 03:05

Xonara


1 Answers

You should put the default arguments in the prototype, not the definition like this:

void arryprnt(int[] a, string intro, int len, string sep=", ", string end=".");

and the make the definition without them:

void arryprnt(int[] a, string intro, int len, string sep, string end) {
    // ...
}

BTW: on another note. It is considered good practice to pass objects which larger than an int by const reference. While this isn't appropriate for all situations, it is appropriate for most and avoids copying things unnecessarily. For example:

void func(const std::string &s) {
    // do some read-only operation with s.
}

func("hello world");
like image 95
Evan Teran Avatar answered Sep 28 '22 07:09

Evan Teran