Understanding void

Apr 2, 2008 at 12:13am
Hi

I'm very new to C++. I'm teaching myself from online tutorials with minimal previous programming experience. I have a question about void. I read that declaring a function void means that that function does not return a value. How can a function not return any value and still contribute to the program? Do I not correctly understand the way the definition uses the term "return"?
Thanks.
Apr 2, 2008 at 12:20am
a fuction is not contribute to a program just by return a value, the main funtion always return 0, this is not all of its contributions.
Apr 2, 2008 at 2:37am
a void function can still perform actions, and there is a way using what are called "references" to get it to pass back modified variable values even though it has no return value as a function.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
#include <iostream.h>

void add(int, int, int&);

int main()
{
  int x, y, z;
  x=2;
  y=3;
  add(x, y, z);
  cout << z << endl;
}

void add(int x, int y, int& z)
{
  z = x + y;
}


this lets main() get a return value for the variable z using a reference (the & symbol), in this case the number 5.
Topic archived. No new replies allowed.