Core C++

Lesson 18 : Arguments and Return Values

This C++ tutorial expands on the material about references and pointers. Here, we cover a wealth of material and give some of the most important uses for references, namely passing arguments by reference. Passing arguments by reference gives us the ability return values through passed in arguments. Below, we illustrate some of the concepts covered in the video with some example functions from finance.

Suppose that we are a banker making a loan of $1000.00 that will paid back in two years at an interest rate of 10 percent per annum. With a yearly interest rate of 10 percent, our payment at the end of two years will be $(1000.00)(1.1)(1.1) = $1210.00. We can write a function to calculate the general payoff for such a loan, like this:

This function takes in the loan payoff value as a reference, which means that when we change its value inside the function the passed in value changes. The principal argument is passed by value, in contrast to the payoff, which is passed by reference. The principal in this case would be 1000. The number of years is passed in by value as a constant. This value is 2, and being a constant enforces the fact that we cannot change its value inside the function. The interest rate is the last parameter and is given a default value of 7 percent. However, since we need a value of 10 percent, we would pass in .1 for this value.

Now suppose that instead of making the loan in one payment, we make it in two: 700 dollars initially and then 300 dollars the next year. We can write a generalized function for taking in a series of loans and generating a payoff. The function below demonstrates how we pass arrays into functions.

In this example, we demonstrate passing in array arguments and setting default value in the function declaration; note that when the declaration is separated from the definition that the default argument is given in the declaration and not the definition. To fully illustrate the usage, we have included an entire program. Notice that the default interest rate is .07 is overridden by the value .1, which we pass in as the last argument. If execute the program, the function calculates this: $((700.00)(1.1) + 300.00)(1.1) = $1177.00. The payoff is less than the first one, since we did not lend the entire $1000.00 for the full two years.

 

© 2007–2024 XoaX.net LLC. All rights reserved.