void function question

Feb 13, 2017 at 3:46am
What would the difference between the two functions? they both work the same way I'm just trying to understand void functions better. The void function is still returning an integer number.

Thanks for your help.

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
  #include "stdafx.h"
#include <iostream>


using namespace std;

void modify(int& z)
{
	cout << "Pick a modification:\n1 - add one \n2 - minus one \n3 - times two\nYour selection is: ";
	int temp;
	cin >> temp;


	if (temp == 1)
		z = z + 1;
	if (temp == 2)
		z = z - 1;
	if (temp == 3)
		z = z * 2;

}

int main()
{
	int a;
	cout << "Enter a number:";
	cin >> a;
	modify(a);
	cout << "\" integer a\" has  been updated to a " << a << endl;
}




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
35
// ConsoleApplication18.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>


using namespace std;

int modify(int& z)
{
	cout << "Pick a modification:\n1 - add one \n2 - minus one \n3 - times two\nYour selection is: ";
	int temp;
	cin >> temp;


	if (temp == 1)
		z = z + 1;
	if (temp == 2)
		z = z - 1;
	if (temp == 3)
		z = z * 2;
	return z;

}

int main()
{
	int a;
	cout << "Enter a number:";
	cin >> a;
	modify(a);
	cout << "\" integer a\" has  been updated to a " << a << endl;
}


Feb 13, 2017 at 3:56am
The void function is still returning an integer number.

void means the function can not return anything.

void modify(int& z)
You're passing arguments by reference, which means the original variable gets modified.
Have a look at "Arguments passed by value and by reference" here
http://www.cplusplus.com/doc/tutorial/functions/

With your modify with an int return value, you can assign it to a variable like so:
1
2
3
4
5
6
7
8
9
int main()
{
    int a;
    cout << "Enter a number:";
    cin >> a;
    int b = modify(a);
    cout << "\" integer a\" has  been updated to a " << a << endl;
    cout << "\" integer b\" has  been updated to a " << b << endl;
}

but you can't do that with a void return value.
Last edited on Feb 13, 2017 at 3:58am
Topic archived. No new replies allowed.