To call a function in our program, we specify the function name followed by empty parentheses as the function has no parameters:
#include <iostream> void myfunction(); // function declaration int main() // w w w .ja v a2s . c o m { myfunction(); // a call to a function } // function definition void myfunction() { std::cout << "Hello World from a function."; }
To call a function that accepts one parameter, we can use:
#include <iostream> int mysquarednumber(int x); // function declaration int main() //w w w. ja v a 2 s . c o m { int myresult = mysquarednumber(2); // a call to the function std::cout << "Number 2 squared is: " << myresult; } // function definition int mysquarednumber(int x) { return x * x; }
We called a function mysquarednumber
by its name and supplied a value of 2 in place of function parameter and assigned the result of a function to our myresult
variable.
What we pass into a function is often referred to as a function argument.
To call a function that accepts two or more arguments, we use the function name followed by an opening parenthesis, followed by a list of arguments separated by commas and finally closing parentheses.
Example:
#include <iostream> int mysum(int x, int y); int main() //from w ww . j a v a 2 s. com { int myresult = mysum(5, 10); std::cout << "The sum of 5 and 10 is: " << myresult; } int mysum(int x, int y) { return x + y; }