Loading, please wait...

Functions

Functions allow you to modularize a program. All variables defined in function definitions are local variables—they’re known only in the function in which they’re defined. Most functions have a list of parameters that provide the means for communicating information between functions. A function’s parameters are also local variables of that function. In programs containing many functions, main is often implemented as a group of calls to functions that perform the bulk of the program’s work. There are several motivations for “functionalizing” a program. The divide-and-conquer approach makes program development more manageable.

 

Another motivation is software reusability—using existing functions as building blocks to create new programs. With good function naming and definition, programs can be created from standardized functions that accomplish specific tasks, rather than being built by using customized code. This is known as abstraction. We use abstraction each time we use standard library functions like printf, scanf, and pow. A third motivation is to avoid repeating code in a program. Packaging code as a function allows the code to be executed from several locations in a program simply by calling the function. Each function should be limited to performing a single, well-defined task, and the function name should express that task. This facilitates abstraction and promotes software reusability.

 

If you cannot choose a concise name that expresses what the function does, it’s possible that your function is attempting to perform too many diverse tasks. It’s usually best to break such a function into several smaller functions—sometimes called decomposition.