C++/More Functions

As mentioned in the previous lesson, functions are building blocks of C++. A function is a named part of a program that can be invoked from other parts of the program as often needed. This chapter introduces the ways by which we pass values to a function.

Function Arguments Passed By Value
In C++, by default variables are passed by value to functions. This means that a copy of the data is made and passed to the function. This is in contrast to passing by reference or by pointer, in which case the address of the object itself is passed to the function. However, let's first look at what passing arguments by value means:

Consider the following program that accepts a number and prints its cube:

If you want the cube of 19, the output should look like this:

Enter a number : 19

The cube of 19 is 6859

That was quite a basic example. I think you got an idea of what a function can do anyways. Let us go a little more complex.

Before looking below, think what the output should be. Probably as the function should work, num1 should be 5 and num2 should be 4. Let's see what the compiler has to say. Number 1 : 4 Number 2 : 5 What? Doesn't that look like the complete opposite to the rules of the language? Seems to be, but isn't. Let us discuss what actually took place. We will need to go into the works of the compiler. A little knowledge is essential to properly understand the functions of the pass by reference and pointers.

Pass By Reference
Now, let's redefine the  function from the above example. The change will be explained in more detail in a later lesson, but let's look briefly at what passing data by reference means.

First the change in the type of the data passed into. Previously the arguments were of type  but they are now of type. The additional  is very important: it tells the compiler that the data is a reference to an int value rather than simply an int value.

The default C++ behavior is to copy the function arguments. The use of a reference type changes this behavior and a copy is no longer made. As an analogy, think of asking someone to proof-read and markup a printed document. You can either give them a photocopy (pass by value) or hand them the original document (pass by reference). In the same way, you can tell the compiler whether to pass a copy of the arguments or the original variables themselves depending on whether you want the originals to be changed or not.

This time the result of the program using pass by reference semantics will be:

Number 1 : 5 Number 2 : 4