2/20/2016
1
C++ PROGRAMMING
Functions
Copyright © 2015 Dan McElroy
Table of Contents
• Introduction to Functions
• Function Parameters and Return Data Type
• Predefined and User Defined Functions
• Scope, Visibility and Lifetime
• Function Prototypes
2/20/2016
2
Functions and Subroutines Serve Two Purposes
• They allow a programmer to say: `this piece of code does a specific job which stands by itself and should not be mixed up with anything else’,
• Second they make a block of code reusable since a function can be reused in many different contexts without repeating parts of the program text.
Functions and Subroutines
Think about a company that has a boss and several employees who each specialize in one task. The boss can say to one person, “Build a thinga-ma-bob and report back to me when you are finished.” This would be like a subroutine. A numeric return value is not returned to the boss by the employee.
To another employee, the boss says, “Count the number of hammers in the tool bin and tell me how many there are.” This is like a function because there is a return value, the count of items.
2/20/2016
3
A Function by Any Other Name
Depending on the computer language that you are using, there are different names that define the same or almost the same thing.
Subroutine: A set of statements that perform a specific task but do not return a value that can be used in an arithmetic expression.
Function: A set of statements that perform a specific task and return a value that can be used in an arithmetic expression.
(NOTE: some functions return non-numeric data)
A Function by Any Other Name
In some languages, a subroutine is called a procedure.
If a subroutine or function becomes part of a class definition in Object Oriented Programming, it is usually referred to as a method.
2/20/2016
4
C and C++ Functions
Visual Basic has both Functions and Subroutines. C and C++ do not make the distinction between functions and subroutines.
In both cases they are called functions. C and C++ declare a function with the void return data type to indicate that there is no return value.
Predefined Functions
C and C++ have a large set of predefined functions. The table below shows some of the predefined functions.
2/20/2016
5
Any Number of Parameters
Functions can have any number of parameters. The data that is passed to a function is called a parameter.
rand( ) no parameters
sqrt(18.0) one parameter
pow(2.0,6.0) two parameters
total(5, 8, 17, 9) four parameters
Sample Functions
double r = rand( ); // returns random #
double x = sqrt(25.0); // √25 = 5.0
double a = pow(5.0, 3.0); // 53 = 125 Two arguments
(pieces of data given to the pow function)
One argument (data given to the pow function)
No arguments (data given to the rand function)
2/20/2016
6
Data Returned into a Variable
double r = rand( ); // returns random #
double x = sqrt(25.0); // √25 = 5.0
double a = pow(5.0, 3.0); // 53 = 125
NOTE: The rand function returns a pseudo random number. The same sequence of numbers is returned unless the program first calls the srand function to 'seed' the random number generator.
Using the Return Value
The return value from a function can be stored in a variable, or the function itself can be part of an expression. // store in a variable double hypotenuse; hypotenuse = sqrt(s1*s1 + s2*s2) ;
// used as part of an expression, hypotenuse + 10 twoLines = sqrt(s1*s1 + s2*s2) + 10.0;
s1
s2
10.0
2/20/2016
7
Sample User Defined Function
// Find the sum of three numbers
double SumOf3(double n1, double n2, double n3) {
double result;
result = n1 + n2 + n3;
return result;
}
One Entry, One Exit
double SumOf3(double n1, double n2, double n3) {
double result;
result = n1 + n2 + n3;
return result;
}
Each function can only have one entry point (the top of the function), and should only have one exit point, the return statement and the end of the block of code. An extra return statement can be placed in the middle of the block of code as part of an if statement, but it is considered bad programming practice.
2/20/2016
8
Defining and Calling a Function double SumOf3(double n1, double n2, double n3) {
double result;
result = n1 + n2 + n3;
return result;
}
A function is defined in one part of the program and a call to the function is activated in another part of the program.
int main(int argc, char* argv[])
{
double x = SumOf3(2.6, 5.8, 11.93);
cout << "x = " << x << endl;
}
Return Data Type
double SumOf3(double n1, double n2, double n3)
{
double result;
result = n1 + n2 + n3;
return result;
}
The return data type can be any type of data, or even class definition. The return data type defines how the function is to look when used as part of an expression. Example:
double x = SumOf3(2.6, 5.8, 11.93);
20.33 The SumOf3 function returns 20.33
2/20/2016
9
The void Return Data Type
void DisplayLargest(double n1, double n2)
{
if (n1 > n2)
cout << n1 << " is larger than " << n2 << endl;
else
cout << n2 << " is larger than " << n1 << endl;
return; // can NOT return a value.
}
If the function is NOT going to return a value, and the function call is not going to be part of an expression, void can be used as the return data type. The return statement is not at the end of the body of the function.
Name of the Function
double SumOf3(double n1, double n2, double n3) {
double result;
result = n1 + n2 + n3;
return result;
}
Any legal name
2/20/2016
10
Parentheses double SumOf3(double n1, double n2, double n3) {
double result;
result = n1 + n2 + n3;
return result;
}
Parentheses directly after a name identifies that a function is either being defined or being called by another part of the program.
When parentheses are used that do not follow a name, they are considered to be part of a mathematical expression.
x = (2 + 3) * 13;
Arguments and Parameters double SumOf3(double n1, double n2, double n3) {
double result;
result = n1 + n2 + n3;
return result;
}
The argument list defines what data and its data type that is to be passed to the function.
The parameter list is the data that is passed to the function.
double x = SumOf3(2.6, 5.8, 11.93);
2/20/2016
11
Curly Braces double SumOf3(double n1, double n2, double n3) {
double result;
result = n1 + n2 + n3;
return result;
}
Curly braces define the block of code that becomes the body of the function.
The return Statement double SumOf3(double n1, double n2, double n3) {
double result;
result = n1 + n2 + n3;
return result;
}
In this example, the SumOf3 function returns a numeric value of type double.
double x = SumOf3(2.6, 5.8, 11.93);
20.33 The SumOf3 function returns 20.33
2/20/2016
12
A Sample Program #include <iostream>
using namespace std;
double Square(double x)
{
return x*x;
}
int main(int argc, char* argv[])
{
double n1;
double n2;
cout << "Enter a number: ";
cin >> n1;
n2 = Square(n1);
cout << "The number squared is: " << n2 << endl;
return 0;
}
Program Execution #include <iostream>
using namespace std;
double Square(double x)
{
return x*x;
}
int main(int argc, char* argv[])
{
double n1;
double n2;
cout << "Enter a number: ";
cin >> n1;
n2 = Square(n1);
cout << "The number squared is: " << n2 << endl;
return 0;
}
The program starts execution at main() Variables n1 and n2 are defined inside of main()
Enter a number:
2/20/2016
13
Program Execution #include <iostream>
using namespace std;
double Square(double x)
{
return x*x;
}
int main(int argc, char* argv[])
{
double n1;
double n2;
cout << "Enter a number: ";
cin >> n1;
n2 = Square(n1);
cout << "The number squared is: " << n2 << endl;
return 0;
}
The cin statement inputs a value from the keyboard and places it into n1
Enter a number: 15
n1 = 15.0
Program Execution #include <iostream>
using namespace std;
double Square(double x)
{
return x*x;
}
int main(int argc, char* argv[])
{
double n1;
double n2;
cout << "Enter a number: ";
cin >> n1;
n2 = Square(n1);
cout << "The number squared is: " << n2 << endl;
return 0;
}
The Square function is called and the value 15.0 is passed by value and shows up in the function as x
Enter a number: 15
n1 = 15.0
15.0
15.0
2/20/2016
14
Program Execution #include <iostream>
using namespace std;
double Square(double x)
{
return x*x;
}
int main(int argc, char* argv[])
{
double n1;
double n2;
cout << "Enter a number: ";
cin >> n1;
n2 = Square(n1);
cout << "The number squared is: " << n2 << endl;
return 0;
}
15.0 * 15.0 is computed which is 225.0
Enter a number: 15
n1 = 15.0
15.0
Program Execution #include <iostream>
using namespace std;
double Square(double x)
{
return x*x;
}
int main(int argc, char* argv[])
{
double n1;
double n2;
cout << "Enter a number: ";
cin >> n1;
n2 = Square(n1);
cout << "The number squared is: " << n2 << endl;
return 0;
}
The value 225.0 is returned by the Square function and stored in n2
Enter a number: 15
n1 = 15.0
n2 = 225.0
225.0
2/20/2016
15
Program Execution #include <iostream>
using namespace std;
double Square(double x)
{
return x*x;
}
int main(int argc, char* argv[])
{
double n1;
double n2; cout << "Enter a number: ";
cin >> n1;
n2 = Square(n1);
cout << "The number squared is: " << n2 << endl;
return 0;
}
The program then displays the result on the console device
Enter a number: 15 The number squared is 225
n2 = 225.0
C/C++ Programming
Scope,
Visibility
and Lifetime
2/20/2016
16
A Quick Review of Variables
Variables have: • A data type (int, double, char, etc.) • A name by which the rest of the program uses
the variable • Memory allocated to hold the data.
Different data type use different amounts of memory. An int uses 4 bytes of memory, a double uses 8 bytes of memory, and a char uses 2 bytes.
Where Is Memory Allocated From? #include <iostream>
using namespace std;
int multiplier = 5; // global variable
void UpdateValue(int); // function prototype
int main (int argc, char* argv[])
{
int value = 10;
UpdateValue (value);
return 0;
}
void UpdateValue(int x)
{
int z = x * multiplier ;
cout << "The value is " << z << endl;
}
The global variable is located outside of any block of code. The memory for the global variable is allocated when the program is compiled.
2/20/2016
17
How Long Is Its Lifetime? #include <iostream>
using namespace std;
int multiplier = 5; // global variable
void UpdateValue(int); // function prototype
int main (int argc, char* argv[])
{
int value = 10;
UpdateValue (value);
return 0;
}
void UpdateValue(int x)
{
int z = x * multiplier ;
cout << "The value is " << z << endl;
}
The global variables remain in memory as long as the program is in memory.
Where Is Memory Allocated From? #include <iostream>
using namespace std;
int Multiplier = 5; // global variable
void UpdateValue(int); // function prototype
int main (int argc, char* argv[])
{
int value = 10;
UpdateValue (value);
return 0;
}
void UpdateValue(int x)
{
int z = x * Multiplier ;
cout << "The value is " << z << endl;
}
An automatic local variable is located with in a block of code defined by the curly braces { }. Memory for automatic local variables is allocated when the function is entered.
2/20/2016
18
Where Is Memory Allocated From? #include <iostream>
using namespace std;
int Multiplier = 5; // global variable
void UpdateValue(int); // function prototype
int main (int argc, char* argv[])
{
int value = 10;
UpdateValue (value);
return 0;
}
void UpdateValue(int x)
{
int z = x * Multiplier ;
cout << "The value is " << z << endl;
}
The function arguments are also automatic local variables argc, argv and x Memory for these variables is allocated when the function is entered.
How Long Is Its Lifetime? #include <iostream>
using namespace std;
int Multiplier = 5; // global variable
void UpdateValue(int); // function prototype
int main (int argc, char* argv[])
{
int value = 10;
UpdateValue (value);
return 0;
}
void UpdateValue(int x)
{
int z = x * Multiplier ;
cout << "The value is " << z << endl;
}
The memory used by the automatic local variables is released as soon as the program exits the block of code.
The memory for argc, argv
and value is released when the program is exited.
The memory for x and z is released when the UpdateValue function is exited.
The data stored in an automatic local variable is lost when the memory for the variable is released.
2/20/2016
19
Local Variable in a for Statement
#include <iostream>
using namespace std;
void CountToTen(); // prototype
int main (int argc, char* argv[])
{
CountToTen();
return 0;
}
void CountToTen()
{
for (int i=1; i<=10; i++)
{
cout << i << endl;
}
}
The variable i is an automatic local variable that exists only while the for statement and its block of code is being executed. i no longer exists in memory and its contents is lost as soon as the for statement is done executing.
Scope and Visibility
#include <iostream>
using namespace std;
void CountToTen(); // prototype
int main (int argc, char* argv[])
{
CountToTen();
return 0;
}
void CountToTen()
{
for (int i=1; i<=10; i++)
{
cout << i << endl;
}
}
The Scope of a variable refers to the part of a program that can access the variable. In order for a variable to be Visible, it must have scope, and it must be defined before an attempt is made to access the variable.
2/20/2016
20
Namespace and Class Scope
Namespace scope gives the program access to names that are declared within the namespace. If you do not want to use the line
using namespace std;
You can explicitly identify the namespace for the cout and cin using the scope resolution operator : :
std::cout << "Enter a number" << std::endl;
Class Scope will be covered when classes are introduced.
C/C++ Programming
Function Prototypes
also known as
Function Declarations
2/20/2016
21
Declare Before Using
C and C++ are single pass compilers. A variable or function must be declared before it can be used. It is common to declare variables at the top of a block of code, but they can be declared anywhere in the block as long as they are declared before being used.
Declare Variables Before Using
#include <iostream> using namespace std; int main(int argc, char* argv[]) { double n1; double n2; cout << "Enter a number: "; cin >> n1; n2 = Square(n1); cout << "The number squared is: " << n2 << endl; return 0; }
Declare before Using
2/20/2016
22
Declare Functions Before Using #include <iostream>
using namespace std;
double Square(double x)
{
return x*x;
}
int main(int argc, char* argv[])
{
double n1;
double n2;
cout << "Enter a number: ";
cin >> n1;
n2 = Square(n1);
cout << "The number squared is: " << n2 << endl;
return 0;
}
Declare before Using
Where Are Functions Placed? #include <iostream>
using namespace std;
int main(int argc, char* argv[])
{
double n1;
double n2;
cout << "Enter a number: ";
cin >> n1;
n2 = Square(n1);
cout << "The number squared is: " << n2 << endl;
return 0;
}
double Square(double x)
{
return x*x;
}
Although functions can be placed before main, it is common to put the functions after main, or even in a different source file. This would result in an undeclared name.
2/20/2016
23
Function Declarations (Prototypes) #include <iostream>
using namespace std;
double Square(double x);
int main(int argc, char* argv[])
{
double n1;
double n2;
cout << "Enter a number: ";
cin >> n1;
n2 = Square(n1);
cout << "The number squared is: " << n2 << endl;
return 0;
}
double Square(double x)
{
return x*x;
}
The function name, return and argument data types can be declared at the top of the program with no body and a semicolon to inform the compiler the interface of the function. The function then can be placed anywhere in the program.
Function Declarations (Prototypes) #include <iostream>
using namespace std;
double Square(double x);
int main(int argc, char* argv[])
{
double n1;
double n2;
cout << "Enter a number: ";
cin >> n1;
n2 = Square(n1);
cout << "The number squared is: " << n2 << endl;
return 0;
}
double Square(double x)
{
return x*x;
}
A function prototype is another name for a function declaration.
The function definition contains the body of the function.
2/20/2016
24
Function Declarations (Prototypes) double Square(double x);
double Square(double);
double GrossPay(double MonthlyPay, int Months);
double ConvertToDouble (string value);
pow (2, 8) --> 2
8 --> 256
pow (8, 2) --> 82 --> 64
Function declarations only need the name of the data types for the return and arguments.
Return and arguments can be of any data type
The order of the function arguments is important
Header Files
A header file typically contains a collection of function declarations (prototypes). The math header file also contains several constants, such as M_PI (3.1415). Header files that are provided by the compiler are usually in the compiler's include directory and are identified by angle brackets around the name of the header file.
Example:
#include <iostream>
#include <cmath>
2/20/2016
25
Header Files
Projects that are built from several C or C++ source files may reference functions in a file other than their own. The function declarations would then be placed in a header file that is referenced by each of the C or C++ source files. Header files that are part of the project have their name enclosed in quotation marks.
Example:
#include "my_functions.h"