Pass by Reference from pass by value code

closed account (4ybDGNh0)
How would I turn this simple void code with one parameter into a pass by reference code (rather than pass by value)??


#include <iostream>
using namespace std;


void boxOffice (int);

int main ()
{
int a=0;

cout<<"Welcome to Pinnochio's Marionette Theater! Please enter patron's age: ";
cin>> a;

boxOffice (a);

return 0;

}

void boxOffice (int a)
{

if (a<=12)
{
cout<<"Ticket Price: $5.00";
}
else if (a<62)
{
cout<<"Ticket Price: $8.00";
}
else if (a>=62)
{
cout <<"Ticket Price: $5.00";
}
cout<<endl;
}
Hi,
So can you make your question a little bit clearer?
closed account (E0p9LyTq)
pass by value (copy):
void boxOffice (int a)

pass by reference:
void boxOffice (int& a)
closed account (4ybDGNh0)
Its for an assignment for one of my classes. We are supposed to have a code where you enter the patron's age and are told a ticket price. We are to use a void function (boxOffice) with one parameter, age. IF you are under 12, ticket price is $5.00, over 62 is $5.00 and anyone else is $8.00. The code I attached is a pass by value and I am wondering how would I alter the code to make it pass by reference?
closed account (4ybDGNh0)
that's it? just adding the & makes it pass by reference?
closed account (E0p9LyTq)
Yup, that's it.

Your code works either way, passing by value or by reference. You are not making a change to the variable a you create in main() when you pass it to your function. You don't need to pass it by a reference, copying a single POD is a very trivial copy operation.
closed account (E0p9LyTq)
You could rewrite your program so it does take advantage of passing by reference, one example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include <iostream>

void boxOffice(int, int&);

int main ()
{
   int a = 0;
   int price = 0;

   std::cout << "Welcome to Pinocchio's Marionette Theater! Please enter patron's age: ";
   std::cin >> a;

   boxOffice(a, price);

   std::cout << "Ticket Price: $" << price << ".00\n";
}


void boxOffice(int a, int& price)
{

   if (a <= 12)
   {
      price = 5;
   }
   else if (a < 62)
   {
      price = 8;
   }
   else if (a >= 62)
   {
      price = 5;
   }
}


Welcome to Pinocchio's Marionette Theater! Please enter patron's age: 28
Ticket Price: $8.00
closed account (E0p9LyTq)
Your boxOffice() function could be streamlined a bit as well, using the logical OR (||)
operator:

1
2
3
4
5
6
7
8
9
10
11
12
void boxOffice(int a, int& price)
{

   if (a <= 12 || a >= 62)
   {
      price = 5;
   }
   else
   {
      price = 8;
   }
}
closed account (4ybDGNh0)
Thanks!!
closed account (E0p9LyTq)
Understanding passing by reference better now?

And you are welcome. :)

In the future, PLEASE use code tags for your source code, as I did. It makes it MUCH easier to read. You could edit your post and add code tags.
http://www.cplusplus.com/articles/jEywvCM9/
Topic archived. No new replies allowed.