Synfire's Guide to C++

6. Functions

Functions allow you to create blocks of code that can be called when needed. This makes programming easier than it was in the old days of carving 1's and 0's into magnetic tape. Back then every time you wanted to do something in your code you had to input it there, now with the introduction of functions you can create a block code that can be executed just by tying the functions name into your program.

As we touched on in the first chapter, a function is defined with a return type, this return type specifies what kind of data the function will return. Lets have a look at a simple program that incorporates the use of functions, the first one don't return a value, while the second demonstrates a returned value and shows how to pass arguments to the function.

func1.cpp
#include <iostream.h>

void Say();
// creates a function without arguments or a return value

int main()
{
    cout << "In main()" << endl;
    Say(); // executes the code in Say()
    cout << "Back in main()" << endl;
    return 0;
}

void Say()
{
    cout << "In Say()" << endl;
}
func2.cpp
#include <iostream.h>

int Add(int x, int y);
int main()
{
    int Num1, Num2;
    unsigned double Answer;
    cout << "Enter the first number: ";
    cin >> Num1;
    cout << "Enter the second number: ";
    cin >> Num2;
    Answer = Add(Num1, Num2); // calls the Add() function
                  // and sends Num1 and Num2 as
                  // arguments. Then the return
                  // value is assigned to Answer.
    cout << Num1 << " + " << Num2 << " = " << Answer << endl;
    return 0;
}

int Add(int x, int y)
{
    return (x+y);
}

Well that covers the basics of functions, As this isn't by no means a definitive guide, it works for what this text is, a tutorial, not a book.

Summary
In this section you learned how to make and use functions. This section did NOT cover setting up local variables, although that was touched on in an earlier chapter, and it didn't go into overloading. If you would like to learn about these things go to a bookstore and get a book on C++ or get on the net and download a tutorial that is specifically about Function Overloading.

< < < Lesson 5: Program Controls | Lesson 7: Arrays > > >



Concerned about phishing or want to know more about it? Then read our fake logins page.