6.8. Functions

Many of the examples you have seen thus far have included the printf statement, but what is printf exactly? printf is a function in the C standard library that prints a string to standard output. A function is a block of code that can be executed from any other point in your program. When you execute a function, you are said to be calling it. When you call a function, your program performs the code in the function body, before returning to the point of the call.

NOTE

The standard library is a collection of functions and constants provided with every C compiler. It includes functions for reading and writing files, and manipulating strings, among other things. C programmers need to use the standard library in virtually every piece of code they write.

Here is a simple example of a function, with calling code:

#include <stdio.h>

int AddFunc(int a, int b) {
    return a + b;
}

int main( const int argc, const char *argv[] ) {
    printf("%d\n", AddFunc(1,2) );
    return 0;
}

This defines a function called AddFunc, which adds two ints together. The function has two parameters, which are called a and b. Parameters are variables that are initialized with values passed to the function when it is called. The values passed are called arguments, and in the preceding example, the arguments to AddFunc are 1 and 2, the numbers appearing in parentheses after AddFunc in the printf statement.

When the function AddFunc is called from inside the printf statement, it initializes the variables ...

Get Beginning Mac OS® X Programming now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.