Home arrow C++ arrow Page 4 - Beginner's Guide to Functions in C++
C++

Beginner's Guide to Functions in C++


Rich is a self-confessed C++ guru! In this article he shows us how functions work in C++ and how to use them in everyday C++programming.

Author Info:
By: Rich C.
Rating: 4 stars4 stars4 stars4 stars4 stars / 235
December 05, 2002
TABLE OF CONTENTS:
  1. · Beginner's Guide to Functions in C++
  2. · A Basic Program
  3. · Using 2 Different Functions
  4. · Functions Calling Other Functions
  5. · Conclusion

print this article
SEARCH DEVARTICLES

Beginner's Guide to Functions in C++ - Functions Calling Other Functions
(Page 4 of 5 )

Functions can also call other functions, just as the Main function called on our 3 different functions above. You can have Main call a function, which calls on another function, which calls on some other function, etc. Lets redesign the above Main program to demonstrate this:

// Main.cpp

#include <fstream.h>

int MultTwo(int,int);
int MultFour(int,int,int,int);
void PrintHead();

int a,b,c,d,e;

int main()
{
PrintHead();
return 0;
}

void PrintHead()
{
cout << "Welcome to Multiply Program!" << endl;
cout << "Written by: Rich C." << endl;
a=1;
b=2;
c=MultTwo(a,b);
d=5;
e=MultFour(a,b,c,d);
cout << e << endl;
}

int MultTwo(int x, int y)
{
return (x*y);
}

int MultFour(int m, int n, int o, int p)
{
return (m*n*o*p);
}


Compile the above program. The result should be '20'.

Now look at how this program is designed. Main only has 1 line of code: a call to the "PrintHead" function. As soon as this function is called, it assigns the same values to our integer variables, calls on our two multiplying functions, and then returns to Main. When program execution returns to Main, the program ends. Please note a very important thing: We can use and manipulate our 5 integer variables in any of these 3 functions because they are GLOBAL variables. If these variables were declared in Main itself, this program would not work.

Why? Because the integer variables would be LOCAL variables to Main, and could only be used by Main. The error you would get from the compiler would be that the functions cannot execute because you are attempting to use integer variables that do not exist in these functions. The same goes for trying to use the variables (x,y,m,n,o,p) used by our functions. You cannot use or manipulate these variables in Main because they are not defined in Main. They are LOCAL variables to their given functions. What Im going to do now is walk through this programs execution step-by-step and demonstrate how all of the variables used by our functions (including Main) are treated by our program. Im going to change the scope of the variables used by the 2 multiplying functions for demonstrative purposes.

Here's the new program:

// Main.cpp

#include <fstream.h>

int MultTwo(int,int);
int MultFour(int,int,int,int);
void PrintHead();

int main()
{
PrintHead();
return 0;
}
void PrintHead()
{
int a,b,c,d,e;

cout << "Welcome to Multiply Program!" << endl;
cout << "Written by: Rich C." << endl;
a=1;
b=2;
c=MultTwo(a,b);
d=5;
e=MultFour(a,b,c,d);
cout << e << endl;
}

int MultTwo(int x, int y)
{
return (x*y);
}

int MultFour(int m, int n, int o, int p)
{
return (m*n*o*p);
}


First thing we do after our header is declare our 3 function prototypes. We then enter Main, at which point this program does not have any variables declared yet. As soon as we enter Main, a function call is made to "PrintHead" and execution leaves Main. "PrintHead" declares 5 new integers and assigns values to 'a' and 'b'.

The "MultTwo" function is then called. The values of 'a and 'b are sent to the "MultTwo" function and are copied into two newly created variables 'x and 'y. Since 'a equals 1, 'x now also equals 1. Since 'b equals 2, 'y now also equals 2. "MultTwo multiplies 'x and 'y together and returns a value of 2 to the "PrintHead" function. Next 'd is assigned a value and all 4 variables, LOCAL to "PrintHead", are sent to "MultFour". This function receives the values of (1, 2, 2, 5) and copies these values into (m,n,o,p). So m=1, n=2, o=2, and p=5. These values are all multiplied together and the result is returned to "PrintHead". This function prints to the screen the value of 'e, at which the function completes its call, and execution returns back to Main to simply end!

Passing By Reference
A function can also receives arguments by reference instead of by value like we have done thus far. In the "Mult" functions above, 2 or 4 values were sent to the appropriate function by value. In other words, when we made a function call, the values of the variables (such as 'a and 'b) were sent to the function as arguments and the function used those values in its body to calculate what it needed to. However, there is another way to get the same results. Instead of actually sending the values of those variables, we can simply send the memory addresses of those variables. You see, when you declare a variable in a program, the compiler reserves a space in memory for that variable. You never decide where in the computers memory this variable will be stored, the computer does that for you. But you can actually find out the exact address of where it is stored, and you can manipulate what is stored there manually. For example, here is a small program that uses only 1 function to add 2 numbers together:

// Main.cpp

#include <fstream.h>

void Add(int, int);

int a,b;

int main()
{
a=1;
b=2;
Add(a,b);

return 0;
}

void Add(int x, int y)
{
int z;

z=(x+y);
cout << z << endl;
}


I decided to use a Void function here just to show you that you can do calculations with Void functions just as easily as value-returning functions. The result printed to the screen at programs end will be '3. Please also note that the variable 'z is LOCAL to the function "Add", and can only be used or manipulated by this function.

Now lets pass arguments to this "Add" function by reference this time to get the same result. The only modification we need to make is to add an ampersand (&) between the argument type and the variable used in the function:

void Add(int& x, int& y)
{
int z;

z=(x+y);
cout << z << endl;
}


This new function receives the memory address of 'a and 'b, not their actual values. The result will be the same however.

Using passing by reference arguments to functions adds a lot of flexibility to your programs, BUT YOU MUST BE CAREFUL! If you change a value stored in a variables memory address, things can go haywire if you didnt intend to. You are actually changing what is in the memory address of the variable. So if you change its value by manipulating its address, the actual value (or integer) will change also. For example, what if the function did this:

void Add(int& x, int& y)
{
x=5;
y=5;
}


In Main, the values of these 2 integers were '1 and '2 accordingly. When this function receives the memory addresses of these two variables, it manipulates these memory addresses and returns to Main. In Main, the values of 'a and 'b are now '5 and '5 accordingly, not '1 and '2 like before. In other words, you reached deep inside the PC, found the addresses of the 2 variables, sent them to a function, the function manipulated the address directly, and the values of these 2 variables are changed for good! This functions prototype must also include the (&) because the compiler must know you intend to pass references to it:

void Add(int&, int&);

Cleaning Up Your Code
When you write programs, you want to make sure that your source code is readable and clearly understandable to you, and anyone else who intends on reading it. This can be done easily with pre-conditions and post-conditions. Pre-conditions describe what arguments, if any, the function receives. Post-conditions detail what the function will do before it returns to the function that calls it. Using our previous function example, lets do this:

void Add(int& a, int& b)
// Pre-conditions: This function will receive two integer references to work with.
// Post-conditions: The values of two integers will be changed to values of '5.
{
a=5;
b=5;
}


Now this function is more readable to everyone.
blog comments powered by Disqus
C++ ARTICLES

- Intel Threading Building Blocks
- Threading Building Blocks with C++
- Video Memory Programming in Text Mode
- More Tricks to Gain Speed in Programming Con...
- Easy and Efficient Programming for Contests
- Preparing For Programming Contests
- Programming Contests: Why Bother?
- Polymorphism in C++
- Overview of Virtual Functions
- Inheritance in C++
- Extending the Basic Streams in C++
- Using Stringstreams in C++
- Custom Stream Manipulation in C++
- General Stream Manipulation in C++
- Serialize Your Class into Streams in C++

Watch our Tech Videos 
Dev Articles Forums 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
Contact Us 
Site Map 
Privacy Policy 
Support 

Developer Shed Affiliates

 




© 2003-2014 by Developer Shed. All rights reserved. DS Cluster - Follow our Sitemap
Popular Web Development Topics
All Web Development Tutorials