C++ Functions

We will be using code written by other programmers a lot in this course. Most of the time we will access this code by calling the code into action using a C++ function. We need to start early in understanding these things, otherwise a lot of your code is not going to make sense!

The easiest way to understand functions is to consider them blocks of code inside a box with a name painted on the outside. Hopefully, the code inside the box does something interesting. It would be especially nice if we needed the code inside the box in several places in our program, but that is not really necessary.

When we want the code inside the box to do its thing, we need a way to activate it. This is called calling the function. Perhaps we need to provide the code inside the box some information that it needs to work, and perhaps the result of activating the code will be to produce some answer that we will take and use in other parts of our program.

Defining a Function

We create a function by coming up with a name, which should describe what the function is going to do for us. Next, we identify any information the function will need to accomplish its task; we call this information parameters. Next, we describe what kind of answer the function will produce (if any); this is called the return value. Finally, we write the code that defines the action of the function.

Here is an example of how it all looks in C++:

float my_sin(float angle) {
    float answer;
    // code to calculate the sin of an angle

    return answer;
}

The first float keyword defines the kind of value the function will return, a floating point number in this case. The name of the function is my_sin. The function needs one piece of data to work with, that parameter will be named angle inside the function, and it is another floating point number.

The body of the function is the code between the curly braces. At some point in that code, we need to include a return statement that causes the function to quit work and hand back the value specified in the statement. The thing after the word return is an expression, usually just the name of the variable you used to calculate the answer, that you want to send back to whoever called this function.

Calling a Function

When we want the code inside the function to do its thing, we call the function by creating a statement that contains the name of the function. That reference will include parentheses inside of which we will provide actual parameters we want the function to use to do its work. The parameters are separated by commas if there are more than one of them.

Parameters can be literal values, or the names of variables defined in our calling code, or expressions the system will evaluate before calling the function. The system will pass the data we specify into the function when the function wakes up. For now, we will assume that the function has no idea where the parameter information came from, it just uses the values passed in and refers to those values using the parameter names we defined when we wrote the function.

Parameter names defined in the function code do not need to be the same as the names from the caller code we place between the parentheses when we call the function.

Phew - sounds complicated, but it is actually fairly simple. (There are more rules on these parameters, but this is enough for now!)

Here is code that demonstrates calling the function:

float mySin, myCos;
float myAngle = 37.0;
float PI = (float)acos(-1.0); // this is a pretty accurate PI

myAngle = myAngle * PI / 180.0;
mySin = my_sin(myAngle);
mySin = my_sin(180 * PI);           // the expression is evaluated and the result passed in

myCos = sqrt(1.0 - my_sin(myAngle)*my_sin(myAngle));        // sqrt is a new function

In each of these examples, the reference to the my_sin function is part of an expression that is being evaluated. Once the entire expression has been evaluated, the value is stored in the container named on the left side of the equal operator. The normal rules of evaluating expressions are still being followed, but when the system gets to the reference to the function, the expression evaluation pauses for a bit while the code for the function figures out the answer needed. That answer is returned to the expression evaluator which continues on with its work.

We will get into all this in more detail soon enough. For now we just need enough information to figure out what our example program is up to.

Since we have not really looked at it, lets open it up and see what we ran:

// Dark GDK - The Game Creators - www.thegamecreators.com

// the wizard has created a very simple 2D project that uses Dark GDK
// it can be used as a starting point in making your own 2D games

// whenever using Dark GDK you must ensure you include the header file
#include "DarkGDK.h"

// the main entry point for the application is this function
void DarkGDK ( void )
{
    // in this application a backdrop is loaded and then several
    // animated sprites are displayed on screen

    // when starting a Dark GDK program it is useful to set global
    // application properties, we begin by turning the sync rate on,
    // this means we control when the screen is updated, we also set
    // the maximum rate to 60 which means the maximum frame rate will
    // be set at 60 frames per second
    dbSyncOn   ( );
    dbSyncRate ( 60 );

    // a call is made to this function so we can stop the GDK from
    // responding to the escape key, we can then add in some code in our
    // main loop so we can control what happens when the escape key is pressed
    dbDisableEscapeKey ( );

    // now we will set the random seed value to the timer, this will
    // help us to get more random values each time we run the program
    dbRandomize ( dbTimer ( ) );

    // we are going to display a backdrop for the scene, to do this
    // we load our image and give it an ID number of 1, this particular
    // image is of a sky at night with stars
    dbLoadImage ( "backdrop.bmp", 1 );

    // the next step is to create a sprite that uses this image, this
    // is achieved by calling dbSprite and passing in a value of 1 for the
    // sprites ID, 0 for the X coordinate, 0 for the Y coordinates and a
    // value of 1 for the image
    dbSprite ( 1, 0, 0, 1 );

    // next we will load in some animated sprites, before doing this
    // we need to adjust the image color key, by using this function we
    // can make a specific color be transparent, in our case we want this
    // to be bright pink
    dbSetImageColorKey ( 255, 0, 255 );

    // in this loop we're going to create some animated sprites, the image
    // we load contains frames of animation for an asteroid
    for ( int i = 2; i < 30; i++ )
    {
            // create an animated sprite and give it the ID number from the
            // variable i, next is the filename, now we come to how many frames
            // across and down, in our case this is 4, finally we come to the image
            // ID that the sprite will use, again we use i
            dbCreateAnimatedSprite ( i, "sprite.bmp", 4, 4, i );

            // position our sprite at a random location
            dbSprite ( i, dbRnd ( 640 ), -dbRnd ( 1500 ), i );
    }

    // now we come to our main loop, we call LoopGDK so some internal
    // work can be carried out by the GDK
    while ( LoopGDK ( ) )
    {
            // run a loop through all our sprites
            for ( int i = 2; i < 30; i++ )
            {
                    // move the sprite down and play its animation
                    // moving from frame 1 to 16 with a delay of 60 ms
                    dbMoveSprite ( i, -2 );
                    dbPlaySprite ( i, 1, 16, 60 );

                    // check the position of the sprite, if it has gone off scren
                    // then reposition it back to the top
                    if ( dbSpriteY ( i ) > 500 )
                            dbSprite ( i, dbRnd ( 640 ), -dbRnd ( 1500 ), i );
            }

            // here we check if the escape key has been pressed, when it has
            // we will break out of the loop
            if ( dbEscapeKey ( ) )
                    break;

            // here we make a call to update the contents of the screen
            dbSync ( );
    }

    // when the user presses escape the code will break out to this location
    // and we can free up any previously allocated resources

    // delete all the sprites
    for ( int i = 1; i < 30; i++ )
            dbDeleteSprite ( i );

    // delete the backdrop image
    dbDeleteImage ( 1 );

    // and now everything is ready to return back to Windows
    return;
}

Phew, that is a lot of code. But stripped of all the comments, it is fairly short:

#include "DarkGDK.h"

void DarkGDK ( void )
{
    dbSyncOn   ( );
    dbSyncRate ( 60 );
    dbDisableEscapeKey ( );
    dbRandomize ( dbTimer ( ) );
    dbLoadImage ( "backdrop.bmp", 1 );
    dbSprite ( 1, 0, 0, 1 );
    dbSetImageColorKey ( 255, 0, 255 );
    for ( int i = 2; i < 30; i++ )
    {
            dbCreateAnimatedSprite ( i, "sprite.bmp", 4, 4, i );
            dbSprite ( i, dbRnd ( 640 ), -dbRnd ( 1500 ), i );
    }
    while ( LoopGDK ( ) )
    {
            for ( int i = 2; i < 30; i++ )
            {
                    dbMoveSprite ( i, -2 );
                    dbPlaySprite ( i, 1, 16, 60 );
                    if ( dbSpriteY ( i ) > 500 )
                            dbSprite ( i, dbRnd ( 640 ), -dbRnd ( 1500 ), i );
            }
            if ( dbEscapeKey ( ) )
                    break;
            dbSync ( );
    }
    for ( int i = 1; i < 30; i++ )
            dbDeleteSprite ( i );
    dbDeleteImage ( 1 );
    return;
}

You can see a lot of `functions in this code. All of them are calling up a lot of code written by advanced graphics game developers and packages in a convenient form for you to use. You just need to learn how to stitch them together. With a little practice, this will make sense. Read over the comments we deleted to get a feel for what is going on. We will get into specifics next.

Table Of Contents

Previous topic

Beginning to program

Next topic

Week 2 Objectives

This Page