C++ Language Tutorial

Functions Primer | C++ Language Tutorial

Welcome to the first lesson of our second chapter. I really hope you have enjoyed Chapter I: The Basics, and that it helped you getting used to the C++ Language. In this chapter, we are going to introduce Functions, and also talk about some other concepts that I have postponed until now, such as Header and Source FilesScope, Global Variables and Static. Shall we get started then?

Functions

You have seen them, used them and you have definitely heard about them. But, what are functions? Simply put, a function is just a group of statements that you can call whenever and wherever you want during the execution of your program. You may say now, that you can already execute whatever statement you want, where you want it and when you want to, but functions provide a functionality without which, everything would have been much more complex and error prone.

Let’s imagine for example that you are developing an application that uses a certain functionality, with several statements, in more than one place. Imagine this group of statements is made out of several calculations and you want to use them in several places in your program. You can, of course, rewrite the statements in every place you wish to execute them, or even copy-paste them. OK, that could work. But imagine now, after you have already used these statements in several places, that you need to change some of the calculations. How would it feel to search through all the lines of code and do the same thing over and over again with every single statement?

That is not a very good practice. Actually this kind of implementation needs to be avoided at all costs.

By using functions, you are also building your application in a modular way, a way that, as you will see, is the key to a good application design. Let’s take a look at how a function looks like:

return_type name ( parameter_1, parameter_2,.., parameter_n ) {
     statement_1;
     .
     .
     statement_n;
}
  • return_type - this is the type of the data returned by the function. This can be any type, such as: intfloatchar etc.
  • name - this is the function identifier which will be used when calling the function.
  • parameter_1..parameter_n - These are the parameters the function accepts, as many as you want/need, or can be omitted. Every parameter is made of a type and an identifier, and its format is just like the one when you declare a variable, for example: int i. These parameters allows us to pass arguments to the function when we cant to call it.
  • statement_1..statement_n - These represent the function body, which consists of a block of statements, just like we’ve seen before, statements enclosed in braces( { and ).

Let’s see an example, for a better understanding of how functions are used:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
//
//  main.cpp
//  ChapterII.FunctionsPrimer
//
//  Created by Vlad Isan on 18/04/2013.
//  Copyright (c) 2013 INNERBYTE SOLUTIONS LTD. All rights reserved.
//
 
#include <iostream>
 
using namespace std;
 
/* 
 Here we are declaring and defining our function, add,
 which has a return type of int, its name is add and it has 2 parameters,
 a and b, both integers.
 */
int add(int a, int b) {
    int result; /* here we are declaring a local variable, result */
 
    result = a + b; /* we are assigning a value to result, which is the addition of our two parameters, a and b */
 
    return result; /* we are now returning with the value of the variable result */
}
 
int main()
{
    int x, y; /* declaration of two integers, x and y */
 
    x = 10; /* assigning values */
    y = 3;
 
    cout << add(x, y); /* We are printing to the screen the result that is retrieved by the function add, which we are calling by passing two arguments, x, and y (10 and 3) */
 
    return 0;
}

This is a simple example of function usage. Let’s go through the code and see what we can note.

The beginning of every program, has the function main as the start point. From there on, the statements are executed sequentially, statement by statement.

In our example, we are first declaring and defining our functionadd, which has a return type of int. It has two parametersand b. In the body of the function we are declaring another variable, result, to which we assign the result from adding the two parameters. And then we are returning from the function with the value of the variable result. As you can see, we must always return with the value the function is declared with.

As said before, the execution of any program starts with the function main, so when our program starts executing, we are declaring two variables, x and y, of type int. Moving on, we are assigning values to them, 10 and 3, in our example. Then, we are calling the function add and passing the two variables, x and y, as arguments. As you can see, when calling a function, we always have to match it’s signature, in our case, the type and number of arguments that we pass to the function when we are calling it, have to match the function‘s signature, two parameters, both integers.

Now, the execution of our program jumps to  execute the functionadd, but before this happens, the current point of execution is marked, so when the function terminates, the execution returns to the same point where the function was called from.

In our example, the function add is called by copying the value of our two variables, x and y, into the local variablesa and b. It then, assigns a local variable, result, which will be assigned to the addition of the two parameters that will contain the values and y contain, in the same order they were passed to the function when called. In our example, a will contain a copy of the value of x, and b will contain a copy of the value of y.

After the addition is finished and the result is assigned to variable result, we are returning from the function with the value variable result had.

In our example, we are using that value to print to the screen. Our program prints out: 13.

After that we are returning from the function main, therefore terminating our program.

As you can see, we are basically using our function as a value. We could have written this in many other ways, and just to point this out, here are some ways in which we can use our function:

    int result = add(x, y) + 25; /* Here we are adding the result returned by calling our function add with the constant 25 */
 
    result = add(result, add(10, 3)); /* Here we are calling our function by passing the result of the same function as the second argument */
 
    cout << result;

You can notice some other ways in which we can call our function. Basically we can use it everywhere we would have used an int value. We can even call a function by passing another function result as an argument, as long as the return type matches the signature of the function we are calling.

Arguments vs Parameters

As you may have noticed by reading this lesson, I have used both of the terms when talking about functions. There are lots of programmers that are using these terms in the wrong way, one instead of the other.

To simply explain it, parameters are the variables that are declared in the function‘s signature, and arguments are the values that we are passing to the function when we are calling it.

Parameters are the variables that are created when the function is called, have a local scope, and are destroyed when the function terminates.

We will talk in the following lessons about the scope of the variables, so you will have a better understanding of it.

Functions with no parameters and/or return type

As I mentioned before, function can have as many parameters as you want, or none. Same goes for the return type. Not every function has to return a value. If there are no parameters, we simply do not declare any of them between the parentheses, ( ). But, how do we go about the return type? This is simple, instead of a return type, we use void type specifier.

Here is an example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
//
//  main.cpp
//  ChapterII.FunctionsVoid
//
//  Created by Vlad Isan on 18/04/2013.
//  Copyright (c) 2013 INNERBYTE SOLUTIONS LTD. All rights reserved.
//
 
#include <iostream>
 
using namespace std;
 
/*
 Declaring a function print, with no return type, void, and no parameters.
 */
void print() {
    cout << "Message from function print()"; /* Here we are printing a message to the screen. */
}
 
int main()
{
    print(); /* Calling function print, with no parameters. */
 
    return 0;
}

As you can see in this example, we are first declaring and defining a new functionprint, which has  no return type, hence the use of the void type specifier, and no parameters, so we simply call it with: print().

We have reached the end of this lesson, in which you have learned the basics about functions.

As always, please do not hesitate to contact me if you have any questions or suggestions.

Leave a Reply