Void Function

Hi guys. So, I'm really new at this programming thing. I'm taking a class right now and in one of the assignments, we are supposed to create a void function that adds 5 to the value that is passed to the function. I can only change the part that is between //s. I thought what I did was right, but the output is exactly the same as the input, so it's not adding 5. Can you help me figure out what I'm doing wrong?

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
 #include <iostream>

using namespace std;
//
void addFive(int number1, int number2, int number3)
{
    number1 = number1 + 5;
    number2 = number2 + 5;
    number3 = number3 + 5;
}
//
int main()
{
     int number1;
     int number2;
     int number3;

     cin >> number1;
     cin >> number2;
     cin >> number3;

     addFive(number1, number2, number3);

     cout << number1 << endl;
     cout << number2 << endl;
     cout << number3 << endl;

     return 0;
}
Inside the void print the numbers you want to print.
Your function doesn't take its parameters by reference, so you are modifying a copy of the numbers, which is why you aren't seeing the results.
OmegaZero69, I don't know what the numbers are, they are generated by the computer when I submit the code.
firedraco, I'm sorry, I have just started learning it, could you explain it more simply?
You need to use reference parameters.

Whats happening in your program right now is that those 3 numbers are passed to the addfive function. Then 5 is added to each of those function. However, the couts in the main function are outputting the ORIGINAL number1, number2, and number3, NOT the modified ones. The modified ones are still in the addfive function. This is because the parameters you sent to the addfive function were merely COPIES and not the actual variables.

To send the actual variables, simply put an ampersand (&) sign after each 'int' of the parameter types.

so: void addFive(int& number1, int& number2, int& number3)

Then run it again and it should work.

You guys are life savers! It worked, thanks!
Topic archived. No new replies allowed.