How C Programming Works

In C, you can add a function definition anywhere within the program (except within another function). The only condition is that you must tell the compiler in advance that the function exists somewhere later in the code. You'll do this with a function prototype at the beginning of the program. The prototype is a statement that looks similar to the first line of the definition. In C, you don't have to give the names of the parameters in the prototype, only the data types. The following is what the function prototype would look like for the doubleAndAdd function:

int doubleAndAdd(int, int);

Imagine function prototypes as the packing list for your program. The compiler will unpack and assemble your program just as you might unpack and assemble a new bookshelf. The packing list helps you ensure you have all the pieces you need in the box before you start assembling the bookshelf. The compiler uses the function prototypes in the same way before it starts assembling your program.

If you're following along with the sample.c program we looked at earlier, open and edit the file to add a function prototype, function definition and function call for the doubleAndAdd function shown here. Then, compile and run your program as before to see how the new code works. You can use the following code as a guide to try it out:

#include <stdio.h>

int doubleAndAdd(int, int);

int main()

{

printf("This is output from my first program!\n");

printf("If you double then add 2 and 3, the result is: %d \n", doubleAndAdd(2,3));

return 0;

}

int doubleAndAdd(int a, int b)

{

return ((2*a)+(2*b));

}

So far we've looked at some basic structural elements in a C program. Now, let's look at the types of data you can work with in a C program and what operations you can perform on that data.

Function Declarations

In C, you'll probably hear the term function declaration more than function prototype, especially among older C programmers. We're using the term function prototype in this article, though, because it has an important distinction. Originally, a function declaration did not require any parameters, so the return type, function name and a pair of empty parentheses were sufficient. A function prototype, though, gives the compiler important additional information by including the number and data types of the parameters it will call. Prototypes have become a best practice approach among coders today, in C and other programming languages.