CS3240: Data Structures and Algorithms

Exercise: Passing Parameters

due Jan 18

C++ allows you to pass parameters in 3 ways: 1) by value, 2) by reference, 3)by constant reference. This exercise has 3 parts and will help you understand the difference. Show results of each part to your instructor.

 

Part 1: Pass by Value

Write a C++ program named MyTestParam1 with a void function called doit(int x)that has one parameter of type int named x. This function should perform the following tasks in order:

  • output value of x
  • increment x by 1 (x = x+1;)
  • output value of x again

The program MyTestParam should create a variable y and do the following in order:

  • print the value of y
  • call the function doit passing it the variable y
  • print the value of y again

What results do you see and why?

 

Part 2: Pass by Reference

Alter the function so that it is a void function called doit(int &x).

Run the program MyTestParam again and observe the differences. What results do you see and why?

 

Part 3: Pass by Const Reference

Alter the function from part 1 so that it is a void function called doit(const int &x).

Try to compile & run the program MyTestParam again and observe the differences. What happened and why? Try removing the x=x+1 line from the function and try to compile&run. What has happened now and why?

 





class Student {





 public:

    String Name;

    int age;

    int SSNum;

    String Advisor;

    void PrintInfo();



}

    





//now in Student.cpp file

void Student::PrintInfo(){

     cout << "Name: " << Name << endl;

     cout << "age: " << age << endl;

     cout << "SS#: " << SSNum << endl;

     cout << "Advisor: " << Advisor << endl;

}

     

© Lynne Grewe