CS110 Lab: C++ Function with Value-parameters

A variable declared in the heading of a function is called a parameter, also called a formal argument or a formal parameter. A variable or expression included in the call to a function is referred to as an argument, also known as an actual argument or actual parameter. Please read the following for further information:

Example

// Program starsNum prints NUM_STARS on the screen.

#include <iostream>
using namespace std;

void PrintStars(int); //Function prototype, with one integer parameter
// Prints NUM_STARS stars on the screen.

int main ()
{
    int NUM_STARS;
    cout  << "How many stars do you want to print out? Enter an integer: ";
    cin >> NUM_STARS;
    cout << endl;
    cout  << "The next line contains "  << NUM_STARS
          << " stars. "  << endl;
    PrintStars(NUM_STARS);  //Function call
    return 0;
}

//**********************************************************************
//Function definition, with one integer parameter
//**********************************************************************

void PrintStars (int numofstars)
// Post: numofstars asterisks are sent to cout.

{
    int i;
    i = 0;
    while (i < numofstars)
    {
	cout << "*";
	i++;
    }
	// Here is a for loop which does the same thing 
	// that the above while loop does.
	//
    	// for (i=0; i < numofstars; i++)
    	// {   
       	//	cout << "*";
    	// }

    cout << endl;
    return;
}                                                               

In the above example, the heading of PrintStars() function is void PrintStars (int numofstars)
The parameter numofstars is a value parameter because its data type int does not end with an ampersand ( & ). When it is called using the argument NUM_STARS, i.e.
PrintStars(NUM_STARS); then parameter numofstars receives a copy of the value of NUM_STARS. At this moment, there are two copies of the data, one in the argument NUM_STARS and one in the parameter numofstars. If a statement inside the function PrintStars were to change the value of numofstars, this change would not affect the argument NUM_STARS.


Copyright: Department of Computer Science, University of Regina.