C / C++ Tutorial Part 4


Functions

Download Source

Functions are something that you use everytime write 'C'. Whether the function is something that comes as part of the package like. "printf" or it is one of your own functions you will end up calling a function.

By splitting your code up into functions you will make the software clearer. Rather than having a long stream of statements you can have a small set of function calls. If you create functions you should think about reuse. Reuse is one of the things that enables you to move forward in writing code, it's so much easier to say , " Oh I've done that before, I've got a function that does it for me.

First steps. Consider this main function ( we've seen plenty of main) :

#include <stdio.h>
void main(void)
{
    int iNum;
    iNum = MyNumberFunction();
    printf("%d",iNum);
}

Just in case it isn't obvious, MyNumberFunction is a made up function.

This program will not compile, try it, prove me wrong.

In order to use one of our functions we first of all have to declare the function. We declare a function by stating how it works before we use it. The things we need in order to tell how it works are :

The function return type, the function name, the data that is needed by the function, i.e.

#include <stdio.h>
int MyNumberFunction(void);
void main(void)
{
    int iNum;
    iNum = MyNumberFunction();
    printf("%d",iNum);
}

This is a declaration for the function I called in main, above. It means we are gong to return an int from the function and we have no parameters into the function (void).

This program will now compile - try it. The program will not link ! We have told the compiler that somewhere there is a function called MyNumberFunction. We need to implement that function.

 

#include <stdio.h>
int MyNumberFunction(void);
void main(void)
{
    int iNum;
    iNum = MyNumberFunction();
    printf("%d",iNum);
}
int MyNumberFunction(void)
{
    return 5;
}

Modules

The function MyNumberFunction does not have to be in the same module as main. We could create a new 'c' file containing the function. We would also create a "h" file which contains the function definition.

Consider this piece of code :

#include <stdio.h>
#include "myfuncs.h"

int main(void)
{
    printf("%d",MyNumberFunction());
    return 0;
}

Now in a new file called myfuncs.h :

int MyNumberFunction(void);
The file myfuncs.c has the following code :

int MyNumberFunction(void)
{
return 5;
}

Thats it. We have just created our own module. In order for us to get this code to compile and link we need to either add the two exe files to the project or edit the makefile. This is beyond the scope of this turorial but if you have any specific problems then e-mail me or post to the learn c-c++ news group ( the address is at the start of tutorial 1 ).


Part 5

Index


Last Updated 8 March 1998 by Nik Swain (email: nikswain@oocities.com)

This page hosted by Geocities Icon Get your own Free Home Page