Functions

As you may have guessed from the programs we have looked at so far, a large program will quickly become very complex. If all the code for even a mid-sized program was placed in the main function, it would be very difficult to read and follow the program, let alone to make changes to it. Also, with a large program the same functionality will often be used in several places. For both these reasons, functions are very useful.

Functions are basically like user defined commands. They allow you to separate out a piece of functionality you are likely to reuse, give it a name and specify arguments that are needed for the code. You can then execute the function elsewhere by simply specifying its name and arguments.

We have seen numerous functions so far. main is a function. printf and scanf are also functions. Functions make programming easier by allowing you to reuse functionality in multiple places in your code. They also make code easier to read because a long block of code can be replaced by a single function call. If the function is named well and a comment is included, this can make a large complicated block of code much easier to follow

Now that the idea of functions has been motivated, lets look at how they are defined and used.

next


 home                      table of contents                      about