Search code examples
visual-c++

How to declare function declaration with default argument value in C++?


Say, I have the following code which uses sum function, which has default value for skip_value argument. The sum function uses default value:

import <print>;
import <vector>;
import <optional>;

std::optional<int> sum(std::vector<int> nums, int skip_value = 100);

int main()
{
  std::vector<int> nums { 10, 20, 30, 100 };
  std::optional<int> result = sum(nums);
  if (result.has_value()) {
    std::println("sum = {}", result.value());
  }
  else {
    std::println("no results were found");
  }
}
std::optional<int> sum(std::vector<int> nums, int skip_value = 100) {
  int result { 0 };
  for (const auto& num : nums) {
    if (num != skip_value)
      result += num;
  }
  if (result == 0) {
    return { };
  } else {
    return result;
  }
}

As you can see, function implementation has default value 100 for skip_value argument. I write the same in function declaration. However, I get the error:

Error C2572 'sum': redefinition of default argument: parameter 1

OK. I change function declaration to the following:

std::optional<int> sum(std::vector<int> nums, int skip_value);

Now I get different error:

Error C2660 'sum': function does not take 1 arguments

How do I do it right?


Solution

  • Use std::optional<int> sum(std::vector<int> nums, int skip_value); in the definition, the default args go in the declaration.

    std::optional<int> sum(std::vector<int> nums, int skip_value = 100);
    
    std::optional<int> sum(std::vector<int> nums, int skip_value) {
      int result { 0 };
      for (const auto& num : nums) {
        if (num != skip_value)
          result += num;
      }
      if (result == 0) {
        return { };
      } else {
        return result;
      }
    }
    

    This should compile.

    See also: Where to put default parameter value in C++?