C++ Helper Functions

Overview

A helper function is merely a function that passes additional arguments to another function of a similar name. The additional arguments that are passed in are usually predetermined by the programmer that allow the use of recursion.

This tutorial considers you are knowledgeable with recursion since our example deals with a recursive function.

Example of a helper function

Below we’ll provide you an example of when you might encounter the use of a helper function. We’ll start off by introducing a simple print function that prints all the elements of a vector.

void print(vector  vec) { 

     for ( int i = 0; i < vec.size(); i++ ) {
          cout << i << ": " << vec[i] << endl;
     }
}



This function would be called in your main program in the following way.

#include 
#include 

using namespace std;

int main() { 

     vector  vec;

     /* Fill the vector with values...using push_back() perhaps? */

     //Calling of our function
     print(vec);

     return 0;
}


Where the helper function comes in

Now, imagine for some reason you want to try making your print function recursively. The thing is, if you want to print using recursion, you need your function to have an additional parameter in order to track what element we are currently printing.

This would mean that we would have to change all our calls to our print function to include an additional parameter. Well, we don't if we use a helper function. By simply having our original print function call our helper function, we avoid changing the names of all our calls.

void print(vector  vec) { 

     print_h(vec, 0);

}

void print_h(vector  vec, int i) { 

    if ( i > vec.size() ) {
        return;
    }

    cout << i << ": " << vec[i] << endl;

    print(vec, i+1);

    return;
}

Related Posts

1 Star2 Stars (1 votes, average: 5.00 out of 5)

No comments yet... Be the first to leave a reply!

blog comments powered by Disqus