|
|
|
|
|
|
|
long FindArea(long length, long width); // returns long, has two parameters
void PrintMessage(int messageNumber); // returns void, has one parameter
int GetChoice(); // returns int, has no parameters
BadFunction(); // returns int, has no parameters |
|
|
|
|
|
|
|
|
Here are some examples of function definitions: |
|
|
|
|
|
|
|
|
long Area(long l, long w)
{
return l * w;
}
void PrintMessage(int whichMsg)
{
if (whichMsg == 0)
cout << Hello.\n;
if (whichMsg == 1)
cout << Goodbye.\n;
if (whichMsg > 1)
cout << I'm confused.\n;
} |
|
|
|
|
|
|
|
|
New Term: Not only can you pass in variables to the function, but you also can declare variables within the body of the function. This is done using local variables, so named because they exist only locally within the function itself. When the function returns, the local variables are no longer available. |
|
|
|
|
|
|
|
|
Local variables are defined like any other variables. The parameters passed in to the function are also considered local variables and can be used exactly as if they had been defined within the body of the function. Listing 5.2 is an example of using parameters and locally defined variables within a function. |
|
|
|
|
|
|
|
|
LISTING 5.2 DEMONSTRATES USE OF LOCAL VARIABLES AND PARAMETERS |
|
|
|
 |
|
|
|
|
1: #include <iostream.h>
2:
3: float Convert(float);
4: int main()
5: {
6: float TempFer;
7: float TempCel;
8:
9: cout << Please enter the temperature in Fahrenheit: ;
10: cin >> TempFer;
11: TempCel = Convert(TempFer); |
|
|
|
 |
|
|
|
|
continues |
|
|
|
|
|