C++ Lesson 3 – Writing Functions

Now we’re going to take a look at function writing in C++. It works exactly the same as writing functions in C. We can either declare at the start of the file and define later. Order is important for the compiler, it needs to at least know the function exists before it is used within your code:

In C++ we can return just about anything, including objects. This includes strings, vectors and the primitives we looked at last time.

With that in mind, we can write functions for the four base mathematical operations, taking two numbers as arguments:

But there is a type of function used in algorithmic programming that allows for divide and conquer approaches and has numerous other applications. These are known as recursive functions. We can examine the example from the C series, for fibonacci sequence generation:

Next time

That’s it for this one, next time we’ll be looking at header files in C++.

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Create your own website, free on WordPress.com.Create your own website.
Start free