C++ function
In C++, functions are a way of grouping a set of related statements into a single unit. Functions allow you to encapsulate a specific task, making it easier to write and maintain your code.
C++ function syntax
1return_type function_name(parameter_list) 2{ 3 // function body 4}
where return_type
is the type of the value that the function returns, function_name
is the name of the function, and parameter_list
is a list of parameters that the function takes.
Let's take a look at some examples of functions in C++.
Example 1: Function Declaration
1#include <iostream> 2using namespace std; 3 4void printMessage() 5{ 6 cout << "Hello World!" << endl; 7} 8 9int main() 10{ 11 printMessage(); 12 return 0; 13}
In the above example, we have declared a function named printMessage
that takes no parameters and returns no value. The function simply prints a message to the screen. The function is called in the main
function by using the function name followed by a pair of parentheses.
The output of the program will be:
Hello World!
Example 2: Function with Parameters
1#include <iostream> 2using namespace std; 3 4void printMessage(string message) 5{ 6 cout << message << endl; 7} 8 9int main() 10{ 11 printMessage("Hello World!"); 12 return 0; 13}
In the above example, we have declared a function named printMessage
that takes a single parameter of type string
named message
. The function simply prints the value of the message
parameter to the screen. The function is called in the main
function by passing a string value as the argument.
The output of the program will be:
Hello World!
Example 3: Function with Return Statement
1#include <iostream> 2using namespace std; 3 4int square(int x) 5{ 6 return x * x; 7} 8 9int main() 10{ 11 cout << square(5) << endl; 12 return 0; 13}
In the above example, we have declared a function named square
that takes a single parameter of type int
named x
. The function calculates the square of the value of x
and returns the result. The function is called in the main
function by passing an integer value as the argument.
The output of the program will be:
25
Example 4: Function Prototype
1#include <iostream> 2using namespace std; 3 4int square(int x); 5 6int main() 7{ 8 cout << square(5) << endl; 9 return 0; 10} 11 12int square(int x) 13{ 14 return x * x; 15}
In the above example, we have declared a function prototype for the square
function in the main
function. The function prototype simply specifies the name, return type, and parameters of the function without providing the function body. The function body is declared after the main
function.
The output of the program will be:
25