What determines whether a function is void-type vs non-void type? Is it the mere presence of the keyword return
in the body of the function? Resources typically say that non-void types
return a value. Why and when should I return a value?
For instance, prefer the code below (code 2
), I didn't need to "return" anything; yet the program worked perfectly.
Compare code 2
to code 1
where I returned a value. Ultimately, it achieved the same purpose. Expanding on the question further, what makes the return type for greet()
in code 3
void?
So I ask again: What determines whether a function is void-type vs non-void type? Is it the mere presence of the keyword return
in the body of the function?
code1:
#include <iostream>
#include <string>
using namespace std;
int dispNumber(int n1) {
return n1;
}
int main() {
int n1 = 22;
cout << dispNumber(n1);
return 0;
}
code 2:
#include <iostream>
#include <string>
using namespace std;
void dispNumber(int n1) {
cout << n1;
}
int main() {
int n1 = 22;
dispNumber(n1);
return 0;
}
code 3
#include <iostream>
using namespace std;
void greet(string n1) {
cout<<"My name is " << n1;
}
int main() {
string n1 = "Fred";
greet(n1);
return 0;
}