AU Chapter 5
AU Chapter 5
Functions
1
What Is a Function?
• Is a subprogram that can act on data and return a value.
• Every C++ program has at least one function, main().
• When your program starts, main() is called automatically.
• main() might call other functions, some of which might call still others.
• Each function has its own name, and when that name is encountered, the execution
of the program branches to the body of that function.
Examples:
Sqrt ( ), maxima( ), tolower ( ) etc.
• When the function returns, execution resumes on the next line of the calling
function.
2
• Functions come in two varieties:
1. User-defined and
2. Built-in
Built-in functions are part of your compiler package-they are supplied by the
manufacturer for your use.
3
Declaring and Defining Functions …cont’d
Function Prototypes
• For functions you write yourself, you must include the prototype.
• The function prototype is a statement, which means it ends with a semicolon.
• It consists of the function's return type, name, and parameter list.
• The parameter list is a list of all the parameters and their types, separated by
commas.
• Note, however, that the function prototype does not need to contain the names of the
parameters, just their types.
• A prototype that looks like this is perfectly legal:
long Area(int, int);
• This prototype declares a function named Area() that returns a long and that has two
parameters, both integers.
• Although this is legal, it is not a good idea.
• Adding parameter names makes your prototype clearer.
• The same function with named parameters might be
long Area(int length, int width);
5
//Demonstrates the use of function prototypes
#include <iostream>
using namespace std;
int FindArea(int length, int width); //function prototype
int main()
{
int lengthOfYard;
int widthOfYard;
int areaOfYard;
areaOfYard=FindArea(lengthOfYard,widthOfYard);
cout << "\nYour yard is " << areaOfYard <<" square feet\n\n";
Output:
return 0;
}
How wide is your yard? 100
int FindArea(int l, int w) How long is your yard? 200
{ Your yard is 20000 square feet
return l * w;
}
6
Defining the Function
• The definition of a function consists of the function header and its body.
• The header is exactly like the function prototype, except that the parameters must
be named, and there is no terminating semicolon.
• The body of the function is a set of statements enclosed in braces.
Shows the header and body of a function.
Function
return type name parameters header
unsigned short int FindArea (int length, int width)
-opening brace
// statements
return (length * width);
keyword return value
- closing brace
Function
body 7
Defining the Function………cont’d
statements;
}
A function prototype tells the compiler the return type, name, and parameter list.
• Functions are not required to have parameters, and if they do, the prototype is not
required to list their names, only their types.
• A prototype always ends with a semicolon (;).
• A function definition must agree in return type and parameter list with its prototype
8
Function Prototype Examples
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
Scope of variables
1. Local Variables
• Variables declared within the function are said to have "local scope."
• That means that they are visible and usable only within the function in which they
are defined.
• 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.
10
//The use of local variables and parameters.
1: #include <iostream>
2: using namespace std;
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);
12: cout << "\nHere's the temperature in Celsius: ";
13: cout << TempCel << endl;
14: return 0;
15: } Output:
16:
Please enter the temperature in Fahrenheit: 212
17: float Convert(float TempFer) Here's the temperature in Celsius: 29.4444
18: {
19: float TempCel;
20: TempCel = ((TempFer - 32) * 5) / 9;
21: return TempCel;
22: }
11
Global Variables
• Variables defined outside of any function have global scope and thus are available from any function in the
program, including main().
• Local variables with the same name as global variables do not change the global variables.
• A local variable with the same name as a global variable hides the global variable, however.
• If a function has a variable with the same name as a global variable, the name refers to the local variable--not the
global--when used within the function.
//Demonstrating global and local variables.
1: #include <iostream>
using namespace std;
2: void myFunction(); // prototype
3: Output:
4: int x = 5, y = 7; // global variables
x from main: 5
5: int main()
6: { y from main: 7
7: cout << "x from main: " << x << "\n"; x from myFunction: 5
9: cout << "y from main: " << y << "\n\n"; y from myFunction: 10
10: myFunction(); Back from myFunction!
11: cout << "Back from myFunction!\n\n"; x from main: 5
12: cout << "x from main: " << x << "\n"; y from main: 7
13: cout << "y from main: " << y << "\n";
14: return 0; }
16: void myFunction()
18: {
19: int y = 10;
20: cout << "x from myFunction: " << x << "\n";
22: cout << "y from myFunction: " << y << "\n\n"; }
12
Variables scoped within a block.
15
Passing by value……..cont’d
a b c x y
Example: int multiply (int, int);
int main() 5 10
{
50
int a, b, c;
a = 2;
b = 5; When the program ends, the variables
c = multiply(a,b); remaining in memory have the values
a = multiply(b,c);
shown in red
return 0;
}
int multiply (int x, int y)
{
x = x * y;
return x;
}
Suppose we want to write a function that swaps two values: that is, value a is
replaced by value b, and value b is replaced by the original value of a. The
function below is an attempt to achieve this goal.
void swap (int x, int y) The function appears to work correctly. The next
{ step is to write a program that calls the function so
int tmp = x; that we can test it:
x = y; int main()
y = tmp; {
} int a=2, b=6;
cout << “Before swap, a=” << a << “ and b=”<< b
<<endl;
Output:
swap(a,b);
Before swap, a=2 and b=6
cout << “After swap, a=” << a << “ and b=”<< b << endl;
After swap, a=2 and b=6
return 0;
}
What went wrong?
• In the swap function, parameters x and y were passed the values of variables a and b
via the function call swap(a, b);
• Then the values of x and y were swapped
• When the function returned, x and y were no longer in memory, and a and b
retained their original values
• Remember, when you pass by value, the parameter only gets a copy of the
corresponding argument; changes to the copy don’t change the original
A demonstration of passing by value.
• When we pass by reference, the data being passed is the address of the argument,
not the argument itself
• The parameter, rather than being a separate variable, is a reference to the same
memory that holds the argument – so any change to the parameter is also a change
to the argument
Revised swap function
void swap (int &x, int &y) The reference designation (&) means that x and y are
{ not variables, but are instead references to the
int tmp = x; memory addresses passed to them
x = y;
y = tmp; If we had the same main program as before, the
} function call:
swap(a,b);
indicates that the first parameter, x, is a reference to a,
and the second parameter, y, is a reference to b
21
How pass-by-reference works
• In the example on the previous slide, x and y referenced the same memory that a
and b referenced
• Remember that variable declaration does two things:
– Allocates memory (one or more bytes of RAM, each of which has a numeric
address)
– Provides an identifier to reference the memory (which we use instead of the
address)
• Reference parameters are simply additional labels that we temporarily apply to the
same memory that was allocated with the original declaration statement
• Note that this means that arguments passed to reference parameters must be
variables or named constants; in other words, the argument must have its own
address
Example
Earlier, we looked at a trace of the program below, on the left. The program on the
right involves the same function, this time converted to a void function with an extra
reference parameter.
int multiply (int, int); void multiply (int, int, int&);
int main() int main()
{ {
int a, b, c; int a, b, c;
a = 2; a = 2;
b = 5; b = 5;
c = multiply(a,b); multiply(a,b,c);
a = multiply(b,c); multiply(b,c,a);
return 0; return 0;
} }
25
A demonstration of multiple return statements.
1:
4: #include <iostream.h>
5:
6: int Doubler(int AmountToDouble);
7:
8: int main()
9: {
11: int result = 0;
12: int input;
13:
14: cout << "Enter a number between 0 and 10,000 to double: ";
15: cin >> input;
16:
17: cout << "\nBefore doubler is called... ";
18: cout << "\n input: " << input << " doubled: " << result << "\n";
19:
20: result = Doubler(input);
21:
22: cout << "\nBack from Doubler...\n";
23: cout << "\ninput: " << input << " doubled: " << result << "\n";24:
25:
Output:
26: return 0; Enter a number between 0 and 10,000 to double: 9000
27: } Before doubler is called...
29: int Doubler(int original) input: 9000 doubled: 0
30: { Back from doubler...
31: if (original <= 10000) input: 9000 doubled: 18000
32: return original * 2;
33: else Enter a number between 0 and 10,000 to double: 11000
Before doubler is called...
34: return -1;
input: 11000 doubled: 0
35: cout << "You can't get here!\n"; Back from doubler... 26
36: } input: 11000 doubled: -1
Default Parameters
• Function call with omitted parameters
– If not enough parameters, rightmost go to their defaults
– Default values
• Can be constants, global variables, or function calls
• Set defaults in function prototype
int myFunction( int x = 1, int y = 2, int z = 3 );
– myFunction(3)
• x = 3, y and z get defaults (rightmost)
– myFunction(3, 5)
• x = 3, y = 5 and z gets default
Ambo University-ECE 27
A demonstration of default parameter values.