Functions

Functions are a good way of cleaning up programs that have a lot of re-used code. This section will demonstrate how to declare and use various functions.

#include <stdio.h>

void printHello(void);
void printInt(int);
int addXY(int, int);

int main()
{
    int x = 2;
    int y = 10;
    int z = 0;

    printHello();
    printInt(x);
    z = addXY(x, y);

    printf("Z is: %i\n", z);

    return 0;
}

void printHello(void)
{
    printf("Hello!\n");
}

void printInt(int a)
{
    printf("%i\n", a);
}

int addXY(int x, int y)
{
    int a = x + y;

    return a;
}

At the top of the source code, underneath #include <stdio.h> and before int main(), are the function prototypes. It is useful to declare a function and use it in your code and have the actual function implementation somewhere else (like a separate file for example). To declare a function prototype, you need to specify its return type (if it doesn't return anything, then use void), its name, and its arguments (if it doesn't have any arguments, like our printHello, then use void). Note that the arguments (variable types) for the function prototype don't need a name yet, so you can use function(int, float, int); for a function that accepts three arguments, those being an integer, a float and an integer, respectively.

At the bottom of the source code, after int main(), are the actual implementations of the functions. printHello(); should be familiar with anyone that has made a hello world in C. It accepts no arguments and doesn't return anything, it simply prints a message.

printInt(a); accepts one integer and simply prints it to the output. Like printHello, this function also does not return anything, it simply prints to the output. Note that the variable a in this function is a local variable, meaning that you can have a separate integer in main called a for example, use it separately, and the code will still compile.

addXY(); takes two arguments, adds them and then returns that value. In this case the returned value is an integer, as the function starts with int. Like all functions (unless specified otherwise), the variables are local.

Inside main(), are the usage of the functions. Calling printHello(); with no arguments, will use that function. Similarly, printInt(x); takes one argument inside the brackets (in this case x) and passes it to the function that prints it to the output. addXY(); accepts two arguments, passes it to its function which then returns the calculated value to be assigned to our z variable. Then we print that value with printf();, a function defined in stdio.h.