C Programming Tutorial 15 – Using Functions in C

Don’t forget to read the last blog about working with strings! Are you new here? Start at the beginning, Intro to C!

We’ve had a small number of videos so far covering C in general. The goal of the previous videos was largely to introduce you to a number of the beginning features of C. As we move on, we’ll go into a bit more detail.

One thing I will discuss in a lot of detail later on is called functions. I thought I would give a blog to introduce them to you so as we use them you are not totally confused.

Functions

A function is essentially a section of code that can be called numerous times. For example, let’s say you are outputting three things to the console, and you are going to do that every minute or so to see how certain data changes over time. So let’s say we are outputting the value of x, y, and also the current time.

Well, the code we would use would look something like:

Then, when we need to output the data again, we can call the same three statements again.

This can work, but it is not the best. For example, let’s say you output this data a few times, but now you changed your mind and would like to update the format that is being outputted. Now you have to go back and change it in every location. This is very error prone.

Instead, we could write what is known as a function, such as printData(), and we would define all of the code to be inside of that function. Later on we will get into how to make functions, but for now let’s just say we made that function and everything is working. Everywhere that used to have the repetitive code can be replaced with a call to that function.

If you want to update the format now, all you have to do is change it in one place, reducing errors and making coding easier.

This is obviously a very simple example, but functions can be used to do a lot of cool complex things. You will see functions every day of your life when programming. In fact, printf() is a function itself. All you have to do is give some data to the printf() function.

So, this blog is more about focusing on using functions rather than creating them, and printf() is a common function that you are going to use. It allows you to give data to be printed. When you give a function data, the computer sciency term is called passing data. Specifically, you can say you are passing data as an argument.

So, let’s say we have something like this:

We are passing two arguments to the printf() function.

Don’t feel like you have to understand everything about functions. Usually functions aren’t really focused on until you have a good understanding of the basics of C programming. Later on we’ll talk about creating function, taking data through parameters, and returning data.

Are you ready to move onto the next blog? We’re going to talk about comments! Let’s go!

Leave a Reply

Your email address will not be published. Required fields are marked *