Default value of function parameter

c++, optional-parameters, syntax

Solution

If you put the declaration in a header file, and the definition in a separate `.cpp` file, and `#include` the header from a different `.cpp` file, you will be able to see the difference.

Specifically, suppose:

lib.h

int Add(int a, int b);

lib.cpp

int Add(int a, int b = 3) {
   ...
}

test.cpp

#include "lib.h"

int main() {
    Add(4);
}

The compilation of `test.cpp` will not see the default parameter declaration, and will fail with an error.

For this reason, the default parameter definition is usually specified in the function declaration:

lib.h

int Add(int a, int b = 3);

Problem

1. ``` int Add (int a, int b = 3); int Add (int a, int b) { } ``` 2. ``` int Add (int a, int b); int Add (int a, int b = 3) { } ``` Both work; which is the standard way and why?

Original source