9

I've just started going through a beginners book of C++. I have some java experience (but having said that, I've never used default arguments in java to be honest)

So, as mentioned, my issue is with default arguments..

This is the code snippet I'm using:

#include <iostream>

using namespace std;

//add declaration
int add(int a, int b);

int main (void)
{
        int number1;

        cout << "Enter the first value to be summed: ";
        cin >> number1;
        cout << "\nThe sum is: " << add(number1) << endl;
}

int add(int a=10, int b=5)
{
        return a+b;
}

The response I get from g++ compiler is: "too few arguments to function 'int add(int, int)'

Am I doing this wrong? (I've also tried it with literal arguments)

P.S. I can't seem to get the code snippet to display properly? Has the system changed?

billz
  • 44,644
  • 9
  • 83
  • 100
yoonsi
  • 754
  • 3
  • 10
  • 23
  • 4
    Default arguments go in the declaration. And to format the code, paste it in, don't put any backticks, highlight it all, and click the {} button. – chris Dec 04 '12 at 23:39
  • 2
    Thank you all gentlemen. I appreciate the fact that I can have an issue solved within seconds by this community. – yoonsi Dec 04 '12 at 23:44
  • There are many good reasons for not using default arguments at all: https://quuxplusone.github.io/blog/2020/04/18/default-function-arguments-are-the-devil/, https://stackoverflow.com/a/51297175/23118 – hlovdal Jul 25 '22 at 10:51

1 Answers1

23

It's the other way around

//add declaration
int add(int a=10, int b=5);


int add(int a, int b)
{
   return a+b;
}

§ 8.3.6 Default arguments A default argument shall be specified only in the parameter-declaration-clause of a function declaration or in a template-parameter. A default argument shall not be specified for a parameter pack.

billz
  • 44,644
  • 9
  • 83
  • 100
  • 9
    If you want to know why, it's because the compiler needs to know the default values at the calling site. The body of the function could be in another file altogether so the information wouldn't be available. – Mark Ransom Dec 04 '12 at 23:43
  • also worth noting, the variable name, in this case `a`, is only required in the function definition(which provides for easier reading and editing, especially when separated over .h and .cpp files). the declaration would look like: `int add(int = 10, int = 5);` and the definition header would simply be `int add(int a, int b)`. Also, you should take out the semi colon after the parameter list in the definition. – Logan Besecker Dec 05 '12 at 00:28
  • Please don't approve [suggested edits](http://stackoverflow.com/review/suggested-edits/1128753) [like this](http://stackoverflow.com/review/suggested-edits/1128250). If needed, refer to [this meta post](http://meta.stackexchange.com/q/157423/187824) for details. – Himanshu Dec 05 '12 at 04:09