We have seen some of the advantages of functions while using the cmath library. Functions are an abstraction. We can use code without worrying about exactly how it works. You probably will never need to look at the code behind the cos function. But as long as we know its name and what parameters it takes, we can make use of it.
Functions also provide an efficient way to reuse code. Instead of calling the cos function when you wanted to do a cosine calculation, you could copy and paste the code for the function into your program. But then you would have to fix any bugs in every place you pasted the code. And if you wanted to change the way the cosine was calculated, you would have to change it in every place you pasted the code. That is a lot of work and a lot of opportunities to make mistakes. The function means we can use that code without copy and paste. If we find a bug in the function, we can fix it in one place and all the places that use it will be fixed.
DRY or βDonβt Repeat Yourselfβ is a widely shared maxim for writing good code. If you find yourself copy/pasting chunks of code while programming, there is probably a better way to solve your problem. Writing a function is one way to reuse logic without repeating it.
Many abstractions are available in the cmath library as well as other C++ libraries. But we can also make our own new abstractionby defining our own functions. A function definition takes this form:
The first line should look familiar - it is the kind of prototype we used while learning about Using math functions from C math. As a reminder, the three parts of that line are:
Given that information, we should be able to use that function to double the value of a number, even if we do not understand exactly how the function does its job. (Being able to use a function without understanding HOW it does its job is one of the key ideas of a function!) Here is a full program that makes use of the double value function:
Note that the function definition for doubleValue is before main, where we make a call to the function. For now, we must always define a function before we try to use it. If you try moving the code for main above the doubleValue definition, the compiler will spit out an error message. When it hits the function call, it has not yet learned about doubleValue.
This simple program sets the value of x to be 5. It then passes x to the double value function in order to calculate y. Unsurprisingly, when we print y, the output is 10.