VOID???

OK, I usually see in programs when a function is being declared??? I dont really know, but here is an example of when it would be used.

void WriteAnswer(int x)
{
using namespace std;
cout << "The answer is " << x << endl;
}

Alright. Sometimes I see void, but most of the time I see int. So is this saying that this function isnt used for integers?

Can you tell me why this is used and what it does?

Thanks!
The type preceding a function name in declaration is the return type.
Void means that nothing is being returned, so you don't need a return statement in your function.

If int is preceding a function name it has to return an int.
That's the return type.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
void myFuncA()
{
     // Don't return anything
}

int myFuncB()
{
     int number = 20;
     return number;
}

bool myFuncC()
{
     if(height == 10)
          return true;
}
Generally the 'void' type is used with a function that doesn't need to return a value. ex:

1
2
3
void outputhello() {
   cout << "Hello!\n";
}


What would be the point in returning anything for this function? It's a very simple example, and can be used in different ways, but that's about it. Something to keep in mind is that you can use 'return;' to end a void function early.

1
2
3
4
5
6
7
8
void loopuntil5() {
   int count=0;
   while(1) {
      cout << "Hello!!!\n";
      count++;
      if(count >= 5) return;
   }
}
Thank you!!! I also have another question.
In the functions, there is always 'return'. Is it OK to use something such as cout just to print the answers?
Unless the return type is void, you have to return the specified type. So just printing the answers inside the function doesn't count as returning something.

If you would rather print inside the function as your answer, use void for the return type.
Alright. Thanks everyone!
Topic archived. No new replies allowed.