0% found this document useful (0 votes)
26 views32 pages

AU Chapter 5

The document discusses functions in C++. It defines a function as a subprogram that can act on data and return a value. It explains how to declare and define functions, including function prototypes, parameters, return types, and scope of variables.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
26 views32 pages

AU Chapter 5

The document discusses functions in C++. It defines a function as a subprogram that can act on data and return a value. It explains how to declare and define functions, including function prototypes, parameters, return types, and scope of variables.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 32

Chapter Five

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.

Declaring and Defining Functions


Using functions in your program you are required to do:
1. Declare the function (declaration)
2. Define the function (definition).
• The declaration tells the compiler the (1) name, (2) return type, and (3) parameters
of the function.
• The definition tells the compiler how the function works.
• No function can be called from any other function that hasn't first been declared.
• The declaration of a function is called its prototype.

3
Declaring and Defining Functions …cont’d

There are three ways to declare a function:


1. Write your prototype into a file, and then use the #include directive to include
it in your program.
2. Write the prototype into the file in which your function is used.
3. Define the function before it is called by any other function. When you do
this, the definition acts as its own declaration, even though not recommended.

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.

unsigned short int FindArea (int length, int width)

return type function name function parameters


parameters 4
Parts of a function prototype
Function Prototypes…..cont’d

• 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;

cout << "\nHow wide is your yard? ";


cin >> widthOfYard;
cout << "\nHow long is your yard? ";
cin >> lengthOfYard;

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

• Function Prototype Syntax

return_type function_name ( [type [parameterName]]...);


• Function Definition Syntax

return_type function_name ( [type parameterName]...)

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

Function Definition Examples

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";
9
}
Execution of Functions
• When you call a function, execution begins with the first statement after the opening
brace ({).
• Branching can be accomplished by using the if statement
• Functions can also call other functions and can even call themselves (this is called
"Recursion," )

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.

1: // Demonstrates variables scoped within a block


3:
4: #include <iostream.h>
5:
6: void myFunc();
7:
8: int main() Output:
9: { In main x is: 5
10: int x = 5; In myFunc, local x: 8
11: cout << "\nIn main x is: " << x;
12:
In block in myFunc, x is: 8
13: myFunc(); Very local x: 9
14: Out of block, in myFunc, x: 8
15: cout << "\nBack in main, x is: " << x;
Back in main, x is: 5
16: return 0;
17: }
19: void myFunc()
20: {
22: int x = 8;
23: cout << "\nIn myFunc, local x: " << x << endl;
24:
25: {
26: cout << "\nIn block in myFunc, x is: " << x;
27:
28: int x = 9;
29:
30: cout << "\nVery local x: " << x;
31: } 13
32: cout << "\nOut of block, in myFunc, x: " << x << endl;
Function Arguments
• Function arguments do not have to all be of the same type.
• It is perfectly reasonable to write a function that takes an integer, two longs, and a character as its
arguments.
Calling a function
• A function is called by specifying its name followed by its arguments.
• Non-value returning functions:
function-name (data passed to function);
• Value returning functions:
results = function-name (data passed to function);
#include <iostream.h>
int FindMax(int, int); // function prototype
int main()
{
int firstnum, secnum, max;
cout << "\nEnter two numbers: ";
cin >> firstnum >> secnum;
max=FindMax(firstnum, secnum); // the function is called here
cout << "The maximum is " << max << endl;
return 0;
}
•The argument names in the function call are referred to as actual parameters
Pass by Value
When arguments are passed by value:
• a copy of each argument value is passed to its respective parameter
• Once the value parameters accepted copies of the corresponding arguments data,
they act as local variables!
• The arguments passed in to the function are local to the function.
• Changes made to the arguments do not affect the values in the calling function.
• the parameter is stored in a separate memory location from the storage location of
the argument, if the argument has one
NB: Parameter is variable in the declaration of function.
• Argument is the actual value of this variable that gets passed to function.
e.g. int max (int x, int y); //function prototype
• Here, parameters x and y are value parameters
• When you call the max function as max(4, 7), the values 4 and 7 are copied to x
and y respectively
• When you call the max function as max (a, b), where a=40 and b=10, the values
40 and 10 are copied to x and y respectively
• When you call the max function as max( a+b, b/2), the values 50 and 5 are
copied to x and y respectively

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;
}

Limitations of pass by value


• Recall that a function can have either one return value or no return value
• If we want a function’s action to affect more than one variable in the calling
function, we can’t achieve this goal using return value alone – remember, our
options are one or none
• The next example illustrates this problem
Example – swap function

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.

1: Demonstrates passing by value


2: Output:
3: #include <iostream.h> Main. Before swap, x: 5 y: 10
4:
Swap. Before swap, x: 5 y: 10
5: void swap(int x, int y);
Swap. After swap, x: 10 y: 5
6:
7: int main()
Main. After swap, x: 5 y: 10
8: {
9: int x = 5, y = 10;
10:
11: cout << "Main. Before swap, x: " << x << " y: " << y << "\n";
12: swap(x,y);
13: cout << "Main. After swap, x: " << x << " y: " << y << "\n";
14: return 0;
15: }
16:
17: void swap (int x, int y)
18: {
19: int temp;
20:
21: cout << "Swap. Before swap, x: " << x << " y: " << y << "\n";
22:
23: temp = x;
24: x = y;
25: y = temp;
26:
27: cout << "Swap. After swap, x: " << x << " y: " << y << "\n"; 19
28:
Pass by Reference
• Builds a better swap function
• Sometimes, we want to change the values of the original function arguments or
return with more than one value from the function, in this case we use reference
parameters
– A reference parameter is just another name to the original argument variable
– We define a reference parameter by adding the & in front of the parameter
name, e.g.
double update (double &x);

• 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

We indicate the intention to pass by reference by appending an ampersand (&) to the


data type of each reference parameter. The improved swap function illustrates this:

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;
} }

int multiply (int x, int y) void multiply (int x, int y, int& z)


{ {
x = x * y; z = x * y;
return x; }
}
swap() rewritten with references.

1: //Demonstrates passing by reference


3: #include <iostream.h>
4: Output:
5: void swap(int &x, int &y); Main. Before swap, x: 5 y: 10
6: Swap. Before swap, x: 5 y: 10
7: int main() Swap. After swap, x: 10 y: 5
8: { Main. After swap, x: 10 y: 5
9: int x = 5, y = 10;
10:
11: cout << "Main. Before swap, x: " << x << " y: " << y << "\n";
12: swap(x,y);
13: cout << "Main. After swap, x: " << x << " y: " << y << "\n";
14: return 0;
15: }
16:
17: void swap (int &rx, int &ry)
18: {
19: int temp;
20:
21: cout << "Swap. Before swap, rx: " << rx << " ry: " << ry << "\n";
22:
23: temp = rx;
24: rx = ry;
25: ry = temp;
26:
27: cout << "Swap. After swap, rx: " << rx << " ry: " << ry << "\n";
28:
}
24
Return Values

• Functions return a value or return void.


• To return a value from a function, write the keyword return followed by the value
you want to return.
• For example:
return 5;
return (x > 5);
return (MyFunction());
• These are all legal return statements, assuming that the function MyFunction() itself
returns a value.
• The value in the second statement, return (x > 5), will be zero if x is not greater
than 5, or it will be 1.
• What is returned is the value of the expression, 0 (false) or 1 (true), not the value of
x.
• It is legal to have more than one return statement in a single function.

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.

1: Demonstrates use of default parameter values


3:
4: #include <iostream.h>
5:
6: int AreaCube(int length, int width = 25, int height = 1);
7:
8: int main()
9: {
10: int length = 100; Output:
11: int width = 50; First area equals: 10000
12: int height = 2; Second time area equals: 5000
13: int area; Third time area equals: 2500
14:
15: area = AreaCube(length, width, height);
16: cout << "First area equals: " << area << "\n";
17:
18: area = AreaCube(length, width);
19: cout << "Second time area equals: " << area << "\n";
20:
21: area = AreaCube(length);
22: cout << "Third time area equals: " << area << "\n";
23: return 0;
24: }
25:
26: int AreaCube(int length, int width, int height)
27: {
28: 28
29: return (length * width * height);
Overloading Functions
• C++ enables you to create more than one function with the same name.
• This is called function overloading.
• The functions must differ in their parameter list, with a different type of parameter,
a different number of parameters, or both.
• Here's an example:
int myFunction (int, int);
int myFunction (long, long);
int myFunction (long);
• Function overloading is also called function polymorphism.
• Poly means many, and morph means form: a polymorphic function is many-formed.
Suppose you write a function that doubles whatever input you give it.
• You would like to be able to pass in an int, a long, a float, or a double.

Without function overloading


With function overloading
int DoubleInt(int);
int Double(int);
long DoubleLong(long);
long Double(long);
float DoubleFloat(float);
float Double(float);
double DoubleDouble(double);
double Double(double);
i.e four function names 29
A demonstration of function polymorphism.
1: Demonstrates function polymorphism
3:
4: #include <iostream.h>
5:
6: int Double(int);
7: long Double(long);
8: float Double(float);
9: double Double(double);
11: int main()
12: {
13: int myInt = 6500;
14: long myLong = 65000;
15: float myFloat = 6.5F;
16: double myDouble = 6.5e20;
17:
18: int doubledInt;
19: long doubledLong;
20: float doubledFloat;
21: double doubledDouble;
22:
23: cout << "myInt: " << myInt << "\n";
24: cout << "myLong: " << myLong << "\n";
25: cout << "myFloat: " << myFloat << "\n";
26: cout << "myDouble: " << myDouble << "\n";
27:
28: doubledInt = Double(myInt); 30
29: doubledLong = Double(myLong);
31: doubledDouble = Double(myDouble);
32:
33: cout << "doubledInt: " << doubledInt << "\n";
34: cout << "doubledLong: " << doubledLong << "\n";
35: cout << "doubledFloat: " << doubledFloat << "\n";
36: cout << "doubledDouble: " << doubledDouble << "\n";
37:
38: return 0;
39: } Output:
40:
myInt: 6500
41: int Double(int original)
42: { myLong: 65000
43: cout << "In Double(int)\n"; myFloat: 6.5
44: return 2 * original; myDouble: 6.5e+20
45: }
46: In Double(int)
47: long Double(long original) In Double(long)
48: { In Double(float)
49: cout << "In Double(long)\n";
50: return 2 * original; In Double(double)
51: } DoubledInt: 13000
52: DoubledLong: 130000
53: float Double(float original)
DoubledFloat: 13
54: {
55: cout << "In Double(float)\n";
DoubledDouble: 1.3e+21
56: return 2 * original;
57: }
58:
59: double Double(double original)
60: {
61: cout << "In Double(double)\n"; 31
62: return 2 * original;
32

You might also like