In C++, functions are fundamental building blocks for structuring code. They promote code reuse and make complex programs easier to manage, understand, and debug.
You can think of a function much like a web development API endpoint - it's a url that performs a specific task and gives a response when called, only in C++ it's a block of code that performs a particular task and gives a response when called. Imagine designing the algorithm that defines how a financial app's "Transfer" button works, that's exactly how functions work.
A function in C++ has the following structure:
- The return type: This indicates what type of data the function will return--for example,
int
for an integer,double
for a double precision floating point, orvoid
if the function does not return a value. - The function name: This is the identifier by which the function can be called.
- The parameters (also called arguments): These are inputs to the function enclosed in parentheses and separated by commas. Parameters are optional; that is, a function may not contain any parameters.
- The function body: This is enclosed in curly braces and contains a collection of statements that define what the function does.
Below is an example of a simple function that adds two integers together and returns the result:
1int add(int a, int b) {
2 return a + b;
3}
This add
function can then be called elsewhere in your code. For instance, to add 10 and 5, you could write: int sum = add(10,5);
. After this line, sum
would contain the value 15.
xxxxxxxxxx
using namespace std;
// Function definition
int add(int a, int b){
return a + b;
}
int main() {
// Function call
int sum = add(10, 5);
cout << "The sum of 10 and 5 is " << sum << endl;
return 0;
}