A function is a group of statements that together perform a task. While no program needs more than a main function, as you write more complex and sophisticated programs, your code will be easier to write, understand, and fix if you divide the code up among different functions, each function performing a specific task.
You implement a function in addition to main by first defining it and then calling it. A function definition consists of a function header and a function body. The function header consists of a return type, a function name , and an argument list. The function header always is followed by an open curly brace , which begins the function body. The function body ends with a close curly brace and contains one or more statements, generally ending with a return statement. Additionally, unless the function is defined above where it is called, it must be prototyped.
In programs where the only function is main, all variables defined at the top of that function necessarily can be accessed throughout the entire program. However, once we start dividing up the code into separate functions, issues arise concerning variable scope and lifetime. A variables scope determines where it can be referred to in the code. A variables lifetime determines when it is destroyed . A local variables scope and lifetime is limited to the function in which it was declared. By contrast, a global variables scope and lifetime are throughout the entire program. Finally, a static local variables scope is limited to the function in which it was declared like a local variable, but its lifetime lasts throughout the entire program like a global variable.
You can pass information to a function by using arguments, and pass arguments by value or by reference. You can also pass a variable argument by value when you dont intend any change to that variable in the called function to affect that variables value in the calling function. Conversely, you pass a variable argument by reference when you intend a change to that variable in the called function to affect that variables value in the calling function. The order and data type of the arguments in the function prototype must correspond to the order and data type of the arguments in the function header. Similarly, the order and data type of the arguments in the function call must correspond to the order and data type of the arguments in the function header.
While arguments are used to pass values to a called function, a return value can be used to pass a value from a called function back to the function that called it. However, while multiple values can be passed to a function as arguments, multiple values cannot be returned from functions.
So far, the variables weve used have only been able to hold one value at a time. In the next chapter, well discuss a type of variable that can hold multiple values simultaneously .