Functions
C++ Functions
Defining C++ Functions
C++ functions use typed parameters and return types.
What is a Function in C++?
In C++, a function is a block of code that performs a specific task. Functions help in organizing code into manageable and reusable sections, making it easier to understand and maintain.
Each function in C++ has a return type, a name, and may have parameters. The return type specifies the type of value that the function returns. If no value is returned, the function's return type is void
.
Function Syntax
The basic syntax of a function in C++ is as follows:
Example of a Simple Function
Let's look at an example of a simple function that adds two integers and returns their sum:
Calling a Function
To use a function, you need to call it. The syntax for calling a function is simply the function name followed by parentheses containing any arguments:
Function Parameters
Function parameters are the variables listed in the function's declaration. In the add
function example, a
and b
are parameters. These act as placeholders for the values you pass to the function when you call it.
Parameters can be of any data type, including custom classes or structures. You can also have functions with no parameters, which are called using empty parentheses.
Return Types
The return type of a function is specified before the function's name in the definition. It indicates what type of value the function will return. If the function does not return a value, the void
keyword is used as the return type.
Here's an example of a function with a void
return type:
This function can be called in the main
function like this:
Functions
- Previous
- Main Function
- Next
- Function Overloading