C++ - c++ function parameters - Programming Languages

Developer’s Guide to C++ Function Parameters

Functions are at the core of the C++ programming language. Without functions, or a snippet of code organized around a single task, your program would not even be able to run. C++ also allows us to declare parameters that make functions easier to write and understand.

Having well-structured functions in your code makes it easier for others to understand what the code does and how to investigate any issues with it. In this article, we cover the basics of functions and how we can use parameters to create streamlined and functional code.

What Is a Function?

To learn how parameters work, we first need to understand functions. In C++, a function represents a group of statements that perform a task, which can be anything from arithmetic to generating a long string of text, from allocating memory to performing a network input/output operation.

You have to declare a function before using it. However, a program won’t execute a function until you call it. Once declared, you can reuse a function as many times as needed in your code. This keeps your code cleaner and more efficient.

While C++ has a library of predefined functions, the programming language lets you define functions of your own. Functions must follow a specific structure, as seen below:

return_type function_name( parameter list ) {
    body of the function
}

The return_type represents the data type you want the function to return. Examples include int, float, and string. A function can also return void, an empty type.

function_name is the place for you to give the function a name that you’ll call in your program. Be sure to assign your function a name that fits its nature.

The parameter list contains the variables we’ll need for our function. You can make this list as long as needed to encompass the variables you need.

Finally, the function will have a group of statements in the body that use parameters to perform a task. It’s also in the body that we will return a value that matches our return type. With an understanding of functions, let’s see how parameters work with functions to create clearer code.

What Is a Parameter?

A parameter is a factor that helps define a function. In C++, parameters are a special type of variable used only during function declarations. The parameter is only accessible within the scope of the function where it’s supplied.

As you create a list of parameters, you must assign a data type to each parameter upon its declaration. This is no different than declaring a variable anywhere else in your code. As with the function itself, you can define parameters as char, int, double, or a number of other data types. Since you can declare each parameter independently, you don’t need to use the same data type for all.

How Do Parameters Work in a Function?

Now that we know what parameters are, let’s look at how function parameters work in C++. 

Take another look at the structure of a function:

return_type function_name( parameter list ) {
    body of the function
}

Following this blueprint, we can create a function of our own:

...void planet(string planetName, int numMoons) {
...
}...

Our function planet requires two parameters, a string and an int. We’ve declared our parameters, but they don’t currently do anything. We need to build the function’s body to determine what we’re creating these parameters to do:

...
void planet(string planetName, int numMoons) {
cout << "The planet " << planetName << " has " << numMoons << " moons.\n";
}
...

Now we have the function planet, which we can call in our program.

Function Parameters in C++ as Part of a Program

Our function does not do anything on its own. We need to call upon planet() in the main section of our code and assign values to our parameters. As mentioned earlier, we can repeat a call to a function as many times as needed. Check out the example below in which we combine our function planet() with main():

...void planet( string planetName, int numMoons ) {
cout << "The planet " << planetName << " has " << numMoons << " moon(s).\n";
}
int main() {    planet("Mercury", 0);
    planet("Venus", 0);
    planet("Earth", 1);
    planet("Mars", 2);
    planet("Jupiter", 79);
    planet("Saturn", 82);
    planet("Uranus", 27);
    planet("Neptune", 14);
  return 0;
}

As you can see, we used the function planet() function eight times, one for each planet in our solar system. Every time we call upon planet(), we need to assign values to each parameter.

The program’s output looks like this:

The planet Mercury has 0 moon(s).
The planet Venus has 0 moon(s).
The planet Earth has 1 moon(s).
The planet Mars has 2 moon(s).
The planet Jupiter has 79 moon(s).
The planet Saturn has 82 moon(s).
The planet Uranus has 27 moon(s).
The planet Neptune has 14 moon(s).

We get a list of each planet and its number of moons.

Pass By Value and Pass By Reference with C++ Function Parameters

Pass by value and pass by reference are both ways of modifying parameters from outside of a function. Let’s see how they work and when to use them.

Pass By Value

With pass by value, local parameters become copies of the original arguments. Changes made to passed arguments have no effect on the original arguments.

Suppose Jupiter picks up a new moon while floating through space. We have a function that allows us to increment Jupiter’s moon counter when this happens:

...
void newMoon(int numMoons)
{
    numMoons++;
}

int main()
{
    int numMoons = 79;
    cout << "Jupiter had " << numMoons << " moons.\n";
    newMoon(numMoons);
    cout << "Jupiter now has " << numMoons << " moons.\n";
    return 0;
}

If we use newMoon() with pass by value, the program preserves the original value of numMoons(). Even though our function increments numMoons(), it retains its value because pass by value creates a copy of the original argument:

Jupiter had 79 moons.
Jupiter now has 79 moons.

Pass by value is helpful when we want to preserve the values assigned to a parameter. To make this program work as intended, though, we need to use pass by reference.

Pass By Reference

We can use pass by reference to let a function modify a variable without creating a copy of it. To do so, we have to use &, which allows us to declare function parameters as references instead. 

See the difference in this example:

...
void newMoon(int &numMoons)
{
    numMoons++;
}

int main()
{
    int numMoons = 79;
    cout << "Jupiter had " << numMoons << " moons.\n";
    newMoon(numMoons);
    cout << "Jupiter now has " << numMoons << " moons.\n";
    return 0;
}

This subtle change is all we need to modify numMoons(). Our increment function now works as intended:

Jupiter had 79 moons.
Jupiter now has 80 moons.

We can actually repeat newMoon() if Jupiter collects more than one new moon.

Functions in C++ Without Parameters

We’ve shown examples of how to create functions with parameters in C++, but you can also create functions without parameters.

A prime example is the main() function. It’s the starting point for any program, and most of the time we use main() without any parameters. This gives us the freedom to input whatever statements we want without having to worry about incorporating certain arguments.

In the example below, we use a basic program to demonstrate that we can fill main() with the code we need to run our program. There is no parameter requirement; you just have to write valid code:

...
int main()
{
    cout << "Hello World!\n";
}

We can also create our own function without parameters. Our program will execute the statements inside the function without requiring any assignments.

In the following example, we create a set of statements to show we can run any code within the planet_list() function. We call upon planet_list() in the main() function and execute it:

...
int main()
{
    void planet_list();
    planet_list();
    return 0;
}

void planet_list()
{
    for (int i = 0; i < 8; i++) {
      string planets[] = {"Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune"};
      cout << planets[i] << endl;
    }
    cout << "This is the list of planets in the solar system.";
}

Here’s the result:

Mercury
Venus
Earth
Mars
Jupiter
Saturn
Uranus
Neptune
This is the list of planets in the solar system.

We can use parameters to reduce the amount of code needed, as in our first example. This shows we don’t need parameters to execute a function.

Learn Programming With Udacity

C++ lets you easily create functions to build out a program. By using parameters, you can make your code more efficient and understandable. Our examples show how to use parameters in functions and how to modify those parameters through passing data.

Ready to start your C++ adventure?

If you’re completely new to programming, check out our Introduction to Programming nanodegree. You’ll learn the basics through practical work in HTML, CSS, and Python.  

If you already have coding experience, consider our specialized C++ Nanodegree program instead. You’ll take your C++ skills to the next level and write five real-world programs of your own.

Complete Code Examples

Example 1: Planet function

#include <iostream>
using namespace std;

void planet( string planetName, int numMoons ) {
cout << "The planet " << planetName << " has " << numMoons << " moon(s).\n";
}
int main() {
    planet("Mercury", 0);
    planet("Venus", 0);
    planet("Earth", 1);
    planet("Mars", 2);
    planet("Jupiter", 79);
    planet("Saturn", 82);
    planet("Uranus", 27);
    planet("Neptune", 14);
  return 0;
}

Example 2: Pass by value

#include <iostream>
using namespace std;

void newMoon(int numMoons)
{
    numMoons++;
}

int main()
{
    int numMoons = 79;
    cout << "Jupiter had " << numMoons << " moons.\n";
    newMoon(numMoons);
    cout << "Jupiter now has " << numMoons << " moons.\n";
    return 0;
}

Example 3: Pass by reference

#include <iostream>
using namespace std;

void newMoon(int &numMoons)
{
    numMoons++;
}

int main()
{
    int numMoons = 79;
    cout << "Jupiter had " << numMoons << " moons.\n";
    newMoon(numMoons);
    cout << "Jupiter now has " << numMoons << " moons.\n";
    return 0;
}

Example 4: Planet list

#include <iostream>
#include <string>
using namespace std;

int main()
{
    void planet_list();
    planet_list();
    return 0;
}

void planet_list()
{
    for (int i = 0; i < 8; i++) {
      string planets[] = {"Mercury", "Venus", "Earth", "Mars", "Jupiter", "Saturn", "Uranus", "Neptune"};
      cout << planets[i] << endl;
    }
    cout << "This is the list of planets in the solar system.";
}