Home arrow C++ arrow Page 2 - 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++ - A Basic Program
(Page 2 of 5 )

Here is an example of a basic program:

// Main.cpp

#include <fstream.h>

int main()
{
int a, b;
a=5;
b=10;
return 0;
}


This program obviously does nothing, but it proves the point that Main must exist and usually returns a zero if the entire program has executed. The shortest program that can exist is this:

// main.cpp

#include <fstream.h>

int main()
{
return 0;
}


This program doesn't do anything either, but if you compile this source code it will execute.

Value-Returning Functions
Sloppy programs written in any language are bad for various reasons. For one, if someone analyzing source code of a badly organized program wants to modify it, it can be rather time-consuming and annoying. If you write a program and decide to modify it in the future, but can't understand how you wrote it or how it works, you're in for some serious trouble. All of this may seem obvious, but it leads into why programmers break up programs into smaller, readable, and understandable segments. For example, beginner programmers write one function (Main), and write 50 lines of source code in Main to develop the program. Sure, the program may work, but future modification of the program may be way too time consuming, if feasible at all. In other words, do yourself a favor; break up programs into small segments! This can be done by designing and using functions. Instead of just having one function working for you in your programs (Main), use several functions (including Main). Let me show you an example:

// Main.cpp

#include <fstream.h>

int a,b,c;

int main()
{
cout << "Welcome to my program!" << endl;
cout << "I can add two numbers together!" << endl;
a=2;
b=3;
c=a+b;
cout << c << endl;
return 0;
}


OK, first we declare three integers before Main (a,b,c). Then we simply assign values to each of them and add them together. We print the result to the screen and that's it, the program ends. Since this program is so short, this program is written fine. However, programming in this fashion is not a good idea when your programs start to become a lot longer and more complex. Also, many of times you will have to do some type of arithmetic with different numbers at different times, which can ultimately lead to very sloppy source code and way too many variables in the program. Here is what I recommend; any time your program needs to do any type of calculation, design a function that can do it for you. To show you how, I'm going to redesign the program above:

// Main.cpp

#include <fstream.h>

int Add(int,int); //function prototype

int a,b,c;

int main()
{
a=2;
b=3;
c=Add(a,b); //function call
cout << c << endl;
return 0;
}

int Add(int a, int b) //function definition
{
c=a+b;
return c;
}


This program produces the same results, but is much cleaner. What we have done is created a function called "Add" that can add any two integer numbers. This function is a value-returning function just like Main is. The first thing we do after our header (fstream.h) is declare this new function "Add" {By the way, the header <fstream.h> is one of the most powerful headers you can use in C++}. This is called a function prototype. It tells the compiler that there is a function outside of main that may be called in the program. A function must be declared before it can be used. Most programmers will do this in the very beginning of their programs, just as we have done here. This prototype must declare its return-type (int), it's name (Add), and its parameters. Parameters can have values, or could have none (such as Main() ).

Parameters tell the compiler what must be sent to the function in order for it to work. For example, when you put a quarter into a candy machine, the quarter is the parameter. It must be inserted into the function (the machine) in order for it to work for you. Our prototype for our "Add" function has two parameters (int,int). Therefore, this function will work as long as we send two integers to it.

We then declare three integers (a,b,c) before Main again. Since these three integer variables are declared outside of Main, they are GLOBAL variables. This means that they can be used or modified anywhere in our program. You'll see the significance of this later. We then assign values to 'a' and 'b' and call our "Add" function to take those values and add them. Notice how the function is called. First we assign the result to 'c'. Before we call this function, 'c' does not have a value yet. When we call this function to work for us, this function will assign the result to 'c'. Both 'a' and 'b' are integers, so this function will work properly. When a function is called, program execution leaves Main and goes to the function. The function will then do it's thing and return a value to Main. This value is assigned to 'c'. When a function returns to Main, program execution goes to the exact spot it left off.

Notice how we define the function. It's declared just like Main is. First we need its return-type (int), then it's name (Add), and then its parameters (arguments). However, notice the 2 differences between the function prototype and the actual function definition. The prototype ends with a semi-colon (;), the function definition does not. In the prototype, the only parameter spec's needed are the type of values needed (int,int). However, the actual function definition must also declare the actual variables that will be used in the function (int a, int b). And then, just like Main, the body of the function is surrounded with braces: { }.

Designing and using a value-returning function requires the following:
  1. Design the function needed by your program on a piece of paper.
  2. Declare the prototype for the function at the beginning of your program (before Main). This prototype must declare the returning value, name, and parameters of the function.

    Example:
    int Add(int a,int b)
    {
    return a+b;
    }
  3. Call the function in Main by setting a variable equal to the result, the function's name, and then its parameter values.

    Example: c= Add(a,b);
  4. Design as many functions as you need using the first four steps. Usually it is a good idea to define each function in the order it is used, one after the other.

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-2017 by Developer Shed. All rights reserved. DS Cluster - Follow our Sitemap
Popular Web Development Topics
All Web Development Tutorials