Functions in C++
Introduction and Summary
Functions are segments of code that serve as the building blocks of a program. Functions modify values, carry out actions, and/or return a value. They are best used to: (1) execute a section of code that would otherwise be repeated, and (2) divide the program into well organized pieces.
Functions can be defined before the definition of the main() function, or they can be declared before it and defined after it. Declaring a function simply means listing its return type, name, and arguments. This line will be the same as the first line of the definition, where the function is actually written. A function can have a void return type if it returns no value. A function should be declared inline if it is short enough that the reward of program speed after compilation outweighs the cost of program size in memory. Inline functions replace the functionality of macros in C. As compiler technology improves it is less and less necessary to explicitly declare functions as inline since newer compilers can decide on their own when inlining is appropriate.
Function names can be overloaded, as long as the different versions differ in return type and/or argument number and/or type. To save the task of defining very similar functions in the case that one argument is not usually important, function arguments can be given default values. Then a call to the function does not have to include a parameter for the argument(s) with defaults if the defaults are acceptable. Another way to save work for the programmer and improve the functionality of the program is to use function templates. These let the programmer define a function for any and all data types in a single definition.