So I'm new to these forums, but i'll ask anyway. I am really confused with the functions in C++ (and we have a test on them tomorrow in my programming class). What is a void function? Why do we put a return statement, instead of changing the value of the variable within the function statement?
Can someone just go over these things briefly? Thanks.
There is no such thing as a 'void function'. However, a function return type can be void, denoting that it does not return any value (but still returns). It is a function the same as any other function, there's nothing special about it.
A function declared with a void return type doesn't return anything. You don't need to put any return statement in the function either. Used when you want to execute some statements, but you don't need to programmatically return a value (ex. printing something to standard output).
Why do we put a return statement, instead of changing the value of the variable within the function statement?
Well, imagine that you had a bunch of functions to do some math (Add, Subtract, Multiply...) and you wanted to do something like (6 * (5 + 8)). If all of our functions returned values, we could just write result = Multiply(6, Add(5, 8));.
However, if we defined our functions to modify arguments, we'd end up with something like:
1 2 3 4 5 6 7
void Add(int a, int b, int& result);
void Multiply(int a, int b, int& result);
int addResult = 0;
int mulResult = 0;
Add(5, 8, addResult);
Multiiply(6, addResult, mulResult);
That is the reason why it is preferred to return something from a function.