1
Posted November 23, 2009 by Spyros in C/C++ Programming
 
 

4. C++ Introduction to Functions

C++
C++

Each C++ program contains at least one function, main(), which signifies the entry point of the program. Think of functions as procedures that execute certain tasks. Functions consist of parameters that actually are auxiliary variables for them. Moreover, they need to return a value, whether that is an integer or a void (meaning no value at all). Whenever we declare a function, its prototype must end with a greek question mark (;)

Int Find (int age,int year);

The above is the prototype of the function Find(). This one returns an integer and has two integer parameters named “age” and “year”. These variables can only be used inside the body of the function. Whenever you declare a function, the names of the parameters can be omitted, but the types must be included. Therefore, this is absolutely legal :

Int Find(int,int);

However, you will find that using names as well can be easier for you in terms of code maintain. If you do not need to return a value, you should declare a function  having “void” as its return type. Let’s see how this works in an actual program :


#include <iostream.h>  // library file for Cout

long Change(int); //declaration of function Change

// function that returns long and has an integer parameter

void main()                 // entry point of our program
{
    int Your_Value;         // declares an integer value
    long My_Value;       // declares a long value

    cout <<"Enter your value:";
    cin >>Your_Value;

    My_Value=Change(Your_Value);
    cout <<"My value now is:";
    cout <<My_Value;
}                // end of main()

long Change(int Your_Value)   // the body of the function, outside main()
{
    long My_Value=Your_Value+5;
    // local variable My_Value becomes Your_Value + 5

    return My_Value;    // returns the value of the My_Value variable.
}      // end of change()

This concludes the basic functions lessons. Let’s now make a small summary before this lesson comes to its end:
1. When we declare a function, we need to specify its return type, parameters and finish the declaration with a greek question mark (;)
2. For the parameters of a function, we do not need to specify their names but their types.
3. The body of a function (apart from main()) is always outside main() itself.
4. The return value of the function should always be the same as they return type declared for the function.
Thanx for reading that, make sure that you read the third part about C++ control structures.


Spyros