Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Advantage of using default function parameter

Tags:

c++

int add (int x, int y=1)
int main ()
{
  int result1 = add(5);
  int result2 = add(5, 3);
  result 0;
}

VS

int add (int x, int y)
int main ()
{
  int result1 = add(5, 1);
  int result2 = add(5, 3);
  result 0;
}

What is the advantage of using the default function parameter, in term of execution speed, memory usage and etc? For beginner like me, I sometimes got confused before I realized this usage of default function parameter; isn't it coding without default function parameter made the codes easier to read?

like image 761
ok_woei Avatar asked Dec 04 '22 09:12

ok_woei


2 Answers

Your add function is not a good example of how to use defaulted parameters, and you are correct that with one it is harder to read.

However, this not true for all functions. Consider std::vector::resize, which looks something like:

template<class T>
struct vector_imitation {
  void resize(int new_size, T new_values=T());
};

Here, resizing without providing a value uses T(). This is a very common case, and I believe almost everyone finds the one-parameter call of resize easy enough to understand:

vector_imitation<int> v;  // [] (v is empty)
v.resize(3);              // [0, 0, 0] (since int() == 0)
v.resize(5, 42);          // [0, 0, 0, 42, 42]

The new_value parameter is constructed even if it is never needed: when resizing to a smaller size. Thus for some functions, overloads are better than defaulted parameters. (I would include vector::resize in this category.) For example, std::getline works this way, though it has no other choice as the "default" value for the third parameter is computed from the first parameter. Something like:

template<class Stream, class String, class Delim>
Stream& getline_imitation(Stream &in, String &out, Delim delim);

template<class Stream, class String>
Stream& getline_imitation(Stream &in, String &out) {
  return getline_imitation(in, out, in.widen('\n'));
}

Defaulted parameters would be more useful if you could supply named parameters to functions, but C++ doesn't make this easy. If you have encountered defaulted parameters in other languages, you'll need to keep this C++ limitation in mind. For example, imagine a function:

void f(int a=1, int b=2);

You can only use the given default value for a parameter if you also use given defaults for all later parameters, instead of being able to call, for example:

f(b=42)  // hypothetical equivalent to f(a=1, b=42), but not valid C++
like image 105
Fred Nurk Avatar answered Dec 28 '22 02:12

Fred Nurk


If there is a default value that will provide correct behavior a large amount of the time then it saves you writing code that constantly passes in the same value. It just makes things more simple than writing foo(SOME_DEFAULT) all over the place.

like image 44
Ed S. Avatar answered Dec 28 '22 01:12

Ed S.