I understand that void returns no values. So how does it work in conjuncture to a function?
My understanding is that the purpose of a function is to return a piece of information after doing something with it.
so why would I want to return no value, and how would this be beneficiary?
3 Answers 3
My understanding is that the purpose of a function is to return a piece of information after doing something with it.
In some (most of the) programming languages, functions have side effects also. Purpose of some functions is limited only to side effects and return value is not necessary. Such functions have void return type.
Some examples of side effects may be:
- Update a global
- File operation, logging etc where user doesn't want to know the status of operation
- Freeing resources
2 Comments
C++ Programming Language Stroustrup 4th Edition book
When declaring a function, you must specify the type of the value returned. Logically, you would expect to be able to indicate that a function didn’t return a value by omitting the return type. However, that would make a mess of the grammar (§iso.A). Consequently, void is used as a ‘‘pseudo return type’’ to indicate that a function doesn’t return a value.
Edit:
When you don't expect something in return to the calling function, we use void function.
3 Comments
void when a function does not return a value?", but "Why would we want a function not to return a value?".the purpose of a function is to return a piece of information - I don't agree with that statement much. That contradicts the concepts of pass by reference.It can be pretty useful for modularizing output. I'll provide you with an example:
#include <iostream>
#include <string>
using namespace std;
void displayMessage(string fName, string mName, string lName, string id);
int main() {
string student[4] = { "Mike", "L.", "Jason", "c23459i" };
displayMessage(student[0], student[1], student[2], student[3]);
return 0;
}
void displayMessage(string fName, string mName, string lName, string id)
{
double PI = 3.14159265359;
cout << "Student " << " information:"
<< "\nFirst name: " << fName
<< "\nMiddle Initial: " << mName
<< "\nFirst name: " << lName
<< "\nID: " << id
<< "\nThe Circumference of a circle with the radius of 2: " << (2*PI*2);
}
You can use void functions IF you don't need to return a value. If you plan to do calculations and return a value such as an int, use a function declaration with the return type of int.
outparams.