-
In C++, when should I use the void command?
Code:
#include <iostream>
#include <math.h>
using namespace std;
int increase(int num);
int decrease(int num);
int main()
{
int n;
cout << "Enter a number and press ENTER: ";
cin >> n;
cout << "Function returned: ";
if (n <= 0)
{
increase(n);
}
else
{
decrease(n);
}
return 0;
}
int increase(int num)
{
for (int n; n <= 0; n++)
{
cout << n << ", ";
}
}
int decrease(int num)
{
for (int n; n >= 0; n--)
{
cout << n << ", ";
}
}
I'm learning functions right now it says in my book that using void won't return a value, however I'm a bit confused by this. When and where should I use the word void? If I change the functions to use void it doesn't change anything in the final result. Hope the question makes since.
Sorry if I didn't really explain what I'm doing here.
-
Defining a function as void means that the function doesn't return any variables. So while your "int increase(...)" function could theoretically return an integer, "void increase(...)" would not return anything. It is useful for lots of things, perhaps most commonly for accessing the properties of an object the Right Way. E.g., "Person.setName(Thomas)", where setName is a void function defined under the Person object, and its purpose is simply to set the Person's name variable to the argument received by the setName function--"Thomas" in this case.
Right now using void functions doesn't change anything in your program's output because your functions aren't set to return anything anyway. That is, you don't have any "return" statements. You could alternatively conclude the increase function, for example, with "return n" and then feed the function itself into cout during the main function (e.g., "cout << increase(num)" or something to that effect; my C++ syntax is very rusty so that may not be exactly correct) and it would display the n variable as returned by the increase function.
It's hard to explain thoroughly without giving example code, which I am too rusty to provide. :P