Function Declarations

Functions consist of a name, a list of parameters that they require and the types of the parameters and the code that should be executed as part of the function. Functions can also return a value when they are called. The type of the data returned is also part of a function. All of these components must be included in a function declaration. The general format for a function is as follows:


<return type> <function name> (<type of arg1> <name of arg1>,  ... <type of argN> <name of argN> )
{

    /*source code*/

    return <value that matches return type>;

}
 

On the next page, we will look at header files, where a prototype of a function can be defined. If a header file is not used, the function must be declared before it is used in the code. For example, if you want to call a function in main, the declaration must appear above main in the source file. The following illustrates a couple of simple functions and how they can be used.
#include <stdio.h>

/*this function will calculate the average of three floats*/
float average3(float value1, float value2, float value3)
{
    float sum = value1 + value2 + value3;

    return (sum / 3.0);
}


int main(int argc, char* argv[])
{
    float a, b, c;
    float avg;

    a = 12.3;
    b = 13.9;
    c = 37.4;

    avg = average3(a,b,c);

    printf("The average of %f, %f, %f is %f\n", a, b, c, avg);

    return 0;
}

next


 home                      table of contents                      about