Example of functions using void and passing by values

To specify that a function does not return a value, we use the void type specifier for the function to indicate to the compiler of the absence of the return type.

For example; 


#include <iostream>
#include<string>
 #using namespace std;

void myName ( string firstName, string lastName)
{
cout<<"My name is "<<firstName<<" "<<lastName;
 }
 int main() {
 myName("Henry","Mosoli");
return 0;
}
My name is Henry Mosoli


void is also used in the function's parameter list to explicitly specify the function to takes no actual parameters when it is called. For example, the exercise could have been declared as:
For example; 



#include <iostream>
 #include<string>
#using namespace std;
void myName ()
{
 string firstName="Henry" string lastName="Musoli" cout<"My name is "<<firstName<<" "<<lastName;
}
 int main()
 {
 myName();
return 0;
}
My name is Henry Mosoli


Note that in calling the function myName we still had to specify the name or the identifier and the empty parentheses. Failure to do that would result in a compilation error.

Back to introduction to functions

No comments:

Post a Comment