Calling Functions


Now that you have defined all the function bodies in the sample application, the last step is to call the functions at the appropriate place in the application.

To call a function, specify its name followed by a pair of parentheses. For example, you can call the DisplayWelcome function as follows:

DisplayWelcome(); 

This is a simple example because the function doesn’t take any parameters or return a value.

If you want to call a function that returns a value, you can assign the return value to a variable. The following example calls the GetInvestmentAmount function and assigns the return value (a double) to a local variable named sum:

double sum = GetInvestmentAmount();
Note

You can ignore the return value from a function if you want. When you call the function, leave out the assignment operator on the left side of the function name. The function still returns the value, but the value is discarded.

If you want to call a function that takes parameters, pass the parameter values between the parentheses in the function call. The following example calls the DisplayProjectedValue function, passing in three literal values as parameters:

DisplayProjectedValue(10000, 25, 6.0);
Note

You don’t specify the parameter data types when you call a function. Just provide the parameter values.

The following example shows how to call a function that takes parameters and returns a value. In this example, we call the GetInvestmentPeriod function to get a value between 5 and 25. We assign the return value to a local int variable named period:

int period = GetInvestmentPeriod(5, 25);

Calling Functions in the Sample Application

In this exercise, you will extend your sample application to include the function calls you’ve just seen.

  1. Continue working with the project from the previous exercise.

  2. Locate the _tmain function. Just after the opening brace ({) of the _tmain function, add the following statement, which calls the DisplayWelcome function:

     DisplayWelcome();
  3. Next add the following statements to display an illustration of investment growth. The DisplayProjectedValue function call will display the value of 10,000 after 25 years at a growth rate of 6 percent.

     Console::WriteLine(S"\nIllustration..."); DisplayProjectedValue(10000, 25, 6.0); 
  4. Next add the following statements to ask the user how much she wants to invest and for how long. The GetInvestmentAmount and GetInvestmentPeriod function calls return these values.

     Console::WriteLine(S"\nEnter details for your investment:"); double sum = GetInvestmentAmount(); int period = GetInvestmentPeriod(5, 25); 

    Note

    The GetInvestmentPeriod function has default values for each of its parameters. (The first parameter has a default value of 10, and the second parameter has a default value of 25.) You can use these default values when you call the function. For example, the following function call uses the default value for the second parameter:

    int period = GetInvestmentPeriod(5); // First parameter is 5; // second parameter // defaults to 25 

    If you use a default value for a parameter, you must use the default values for each subsequent parameter in the parameter list. For example, the following function call is invalid:

    int period = GetInvestmentPeriod(, 20); // Try to use default value // for just the first // parameter – illegal.

  5. Now add the following statements to calculate and display the projected final value of this investment, assuming a growth rate of 6 percent:

     Console::WriteLine(S"\nYour plan..."); DisplayProjectedValue(sum, period, 6.0);
  6. Build your program, and fix any compiler errors. Now run the program, and you should see output similar to the following graphic.

    click to expand

Stepping Through the Application with the Debugger

In this exercise, you will step through the application with the debugger. Doing so will help you understand how the flow of control passes from one function to another in your application. This exercise will also illustrate the concept of variable scope. You will see how local variables in a function come into scope during the function’s execution and disappear from scope at the end of the function.

  1. Open the project from the previous exercise.

  2. Locate the _tmain function.

  3. Insert a debug breakpoint by clicking in the gray border to the left of the code. Click next to the DisplayWelcome function call, and you should see a red dot appear in the border, as shown in the following graphic.

    click to expand

  4. Start the debugging session by pressing F5. Once the program has loaded, it will execute and stop at the breakpoint in the _tmain function.

    click to expand

    A yellow arrow appears in the margin next to the DisplayWelcome function call. The yellow arrow indicates that this is the next statement to be executed.

  5. Press F11 to step into the DisplayWelcome function. This debugger calls the DisplayWelcome function and displays a yellow arrow at the start of that function.

    click to expand

    Note

    You can also use the Debug toolbar to control the debugger. You can display the Debug toolbar by selecting Toolbars from the View menu and then choosing Debug from the list of toolbars. Each of the debug function keys mentioned in the remainder of this exercise has an equivalent Debug toolbar button.

  6. Press F10 several times to step over each statement one at a time in the DisplayWelcome function, which will cause a welcome message to be displayed in the console window. At the end of the function, the debugger will return you to the _tmain function. The yellow arrow indicates the next statement to execute in _tmain.

    click to expand

  7. Press F10 to step over the Console::WriteLine function. The debugger executes the Console::WriteLine function but doesn’t take you through it step by step. The yellow arrow moves on to the DisplayProjectedValue function call in _tmain.

  8. Press F11 to step into the DisplayProjectedValue function. From the Debug menu, select Windows and then Locals. The local variables in this function will be displayed.

    click to expand

    The Locals window displays five local variables. The first three variables—amount, years, and rate—are the function parameters. These variables are already initialized with the values you passed into the function.

    The last two variables—finalAmount and rateFraction—do not have meaningful values because the variables haven’t been assigned a value yet. In fact, the debugger is a little misleading here because the finalAmount and rateFraction variables haven’t been declared yet. These variables don’t really exist until the variable declaration statements further on in the function.

  9. Press F10 several times to step over the statements in the DisplayProjectedValue function. Observe how the finalAmount and rateFraction variables change during the function. (The debugger displays values that were changed during the execution of the previous statement in red for prominence.) Take a look at the console window to see what is displayed.

  10. Keep pressing F10 until you reach the end of the DisplayProjectedValue function, and return to _tmain.

  11. In _tmain, press F10 to step over the Console::WriteLine statement.

  12. Press F11 to step into the GetInvestmentAmount function. Step through the statements in this function. When the debugger executes the ReadLine statement, the console window appears and you are asked to enter a number. Enter a number such as 20, and press Enter.

  13. Keep stepping through the GetInvestmentAmount function until you return to _tmain.

  14. Press F10 one more time, and then examine the local variables in _tmain. Notice that the return value from GetInvestmentAmount has been assigned to the sum local variable in _tmain.

    click to expand

  15. Continue stepping through the application in this manner until the application terminates.

Tip

If the debugger takes you into a function that you’re not interested in stepping through, press Shift+F11 to step out of the function. If you just want to run the application without stopping at all, press F5.

Understanding Local and Global Scope

As you saw in the previous exercise, each function defines its own scope for local variables. The local variables are created during function execution and are automatically destroyed at the end of the function, which means you can quite happily have variables with the same name in different functions without interference.

It’s also possible to declare variables globally, outside of any function. Global variables are visible in all function bodies that come after the global variable definition in your source file. You can use global variables as a rudimentary way of sharing information between multiple functions.

Important

Global variables are generally considered bad programming practice, especially in object-oriented languages such as C++. Global variables have too much visibility. Because global variables can often be used in several functions, if one gets corrupted, it can be difficult to pinpoint where the problem occurred. Global variables also introduce too much dependency between functions.

For these reasons, you should use global variables sparingly. A better way of sharing information between functions is to pass parameters and return values, as you saw earlier in this chapter.

In this exercise, you will define a global variable in your application. You will use this global variable in several functions to illustrate its global scope.

  1. Continue working with the project from the previous exercise.

  2. Before the start of the _tmain function, define a global integer variable named numberOfYourFunctionsCalled, as follows:

    int numberOfYourFunctionsCalled = 0;

    click to expand

  3. Find the DisplayWelcome function in your code. At the start of this function, increment the numberOfYourFunctionsCalled variable as shown in the following graphic.

    click to expand

  4. Add a similar statement to the start of every function in your
    application.

  5. Modify the _tmain function. At the end of this function, just before the return statement, display the value of the numberOfYourFunctionsCalled variable.

    click to expand

  6. Build and run your program. How many of your functions are called during the program?

Overloading Functions

Visual C++ lets you provide many functions with the same name, as long as each function has a different parameter list. This process is known as function overloading. Function overloading is useful if you have several different ways of performing a particular operation based on different input parameters.

For example, you might want to provide an average function to find the average value of two double values, and you might have another average function to find the average value of an array of integers. You can define two functions to support these requirements. Give each function the same name, average, to emphasize the common purpose of these functions. Define different parameter lists for the functions to differentiate one from another.

double average(double number1, double number2); double average(int array[], int arraySize);

You must still implement both of these functions—there is no magic here! When you call the average function, the compiler deduces which version of the function to call based on the parameter values you supply.

Note

If you define overloaded functions, the functions must have different parameter lists. If you define overloaded functions that differ only in their return type, you’ll get a compiler error.

In this exercise, you will define an overloaded version of the DisplayProjectedValue function. The new version will calculate a random growth rate between 0 and 20 percent, rather than use a specific growth rate.

  1. Continue working with the project from the previous exercise.

  2. Add the following function prototype at the start of your code, near the other function prototypes:

    void DisplayProjectedValue(double amount, int years);
  3. In the _tmain function, locate the second call to the DisplayProjectedValue function. Modify the function call so that you pass only two parameters into the function.

    DisplayProjectedValue(sum, period);
  4. At the end of the program, define the new DisplayProjectedValue function body as follows:

    void DisplayProjectedValue(double amount, int years) { numberOfYourFunctionsCalled++; Random __gc * r = new Random(); int randomRate = r->Next(0, 20); DisplayProjectedValue(amount, years, randomRate); }

    This function uses the Random class to calculate a random number between 0 and 20. The function passes the random number into the original version of the DisplayProjectedValue function to calculate the value of the investment using this random rate.

  5. Define breakpoints at the start of both of the DisplayProjectedValue functions.

  6. Build the program, and start it in the debugger.

  7. Observe which versions of DisplayProjectedValue are called as your program executes. See what random number the program uses for your growth rate.

  8. Run the program several times to verify that the growth rate really is random.




Microsoft Visual C++  .NET(c) Step by Step
Microsoft Visual C++ .NET(c) Step by Step
ISBN: 735615675
EAN: N/A
Year: 2003
Pages: 208

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net