Skip to main content

Functions and Prototypes

Where should a function's definition go in relation to the entire program - before or after main()? The only requirement is that the function's type has to be known before it is actually used. One way is to place the function definition earlier in the program than it is used - for example, before main(). The only problem is that most C programmers would rather put the main program at the top of the program listing. The solution is to declare the function separately at the start of the program. For example:

int sum();

main()

{

etc...

declares the name sum to be a function that returns an integer. As long as you declare functions before they are used you can put the actual definition anywhere you like.

By default if you don't declare a function before you use it then it is assumed to be an int function - which is usually, but not always, correct. It is worth getting into the habit of putting function declarations at the start of your programs because this makes them easier to convert to full ANSI C.