Question about Void-Functions!

Hello,

I have been studying for this Wednesday exam but still cannot find a difference between a void function and the usual user-defined functions!

can someone explain the difference. plus, briefly explain void functions and what are the usual mistakes for students and what they (we) usually miss.

thank you,
A void function is a function that does not return a value. That's about it.
closed account (2LzbRXSz)
Well, the major (and really only) difference is that a void function doesn't return a value, where other functions do. Some people use void functions where other functions could have been more efficient, and vice versa.

Here's an example of their difference:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>

using namespace std;

void addition(int &num)
{
    num = num + 1;
}

int main()
{
    int number = 4;
    
    addition(number);
    
    cout << number;

    return 0; 

}

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

using namespace std;

int addition(int &num)
{
    num = num + 1;
    
    return num;
}

int main()
{
    int number = 4;
    
    cout << addition(number);

    return 0; 
   
}


In the void example, we take number, and pass it through a function that change it's value to number + 1; Once it's value has been changed, we display the value of number.

The int example does the same exact thing, except, we can display the value returned by the function (no need to go the extra step of writing cout << number; after the function call!)

Void functions do not have a return value, so you can't cout it's value.

In the int addition example, you could also define another int that is equal to the return value of the function...
int foo = addition(num);

You would not be able to do this with a void function, because it doesn't return a value.

There are more complex situations, and better reasons that show when to use what. You'll know when the time comes which one to use. I know when I was a beginner I went crazy with void functions - didn't bother using any other types! I figured why bother with a return value when I've got the handy dandy address of operator (&) (which I wasn't even using correctly)!

Feel free to read more about functions
http://www.cplusplus.com/doc/tutorial/functions/

And about void types
http://en.wikipedia.org/wiki/Void_type

A thread about void v.s. int (pretty much explains the same idea)
http://stackoverflow.com/questions/7707604/void-vs-int-functions
Last edited on
Topic archived. No new replies allowed.