Welcome to our lesson on C++ functions! Functions form the building blocks of any program by encapsulating chunks of code into reusable modules, which are key to constructing complex code. Let's explore further!
Have you ever used a recipe? If so, you've employed a real-world function, albeit an ad hoc one. A function is a set of instructions designed to accomplish a specific task. Functions help package blocks of code into reusable components, a concept known as code reusability.
Every C++ function consists of a name, a return type, and a parameter list, forming the following syntax:
Let's break down each part.
Let's consider a function without arguments that prints a greeting in the console. It doesn't take any parameters, and a void
return type specifies it doesn't return a value.
Example function:
Example function call:
While this function might seem not very useful, it already brings out the most significant advantage of using function: reusability! We can call this function as many times as we want without rewriting its code:
Let's consider a function with arguments, which can accept parameters, It will still have a void
return type, meaning it doesn't return a value.
Example function:
This function prints out a personalized greeting, using the provided name. Here is an example code:
Now, our program is more friendly!
Let's consider a function with multiple parameters:
This function takes two numbers as arguments. It calculates and prints their sum.
Example function call:
While printing the sum this easy is awesome, it is not the optimal design for your code. A function is supposed to be as general as possible: we must be able to reuse it in different scenarios. With that said, it is more common to define a function that both accepts arguments and returns a value.
Example function:
Here is how we call it:
Note that we still print the sum, but not directly in the function. We first put the result into a variable and then print it. The advantage of it is that we can now use the function in cases where we don't need to print the sum. For example:
Here, we use the result of our function as an intermediate step for some calculation.
Today, we've learned the basics, components, and applications of functions. We've understood how to declare, define, and call a function, and how to understand function arguments and return values. Practice makes perfect, so prepare for hands-on exercises to sharpen your programming skills. Keep coding!
