Unit4 Functions C++ PDF
Unit4 Functions C++ PDF
C/C++ Functions
Mark Redekopp
2
A QUICK LOOK
3
Function Signatures/Prototypes
• Also called procedures or methods
• We think of a function as a blackbox (don't
know or care how it does the task a b
internally) where we can provide inputs
and get back a value max
• A function has:
– A name int max(int a, int b);
– Zero or more input parameters Function Signature/Prototype
Execution of a Function
#include <iostream>
• Statements in a function are executed using namespace std;
// prototype / declaratoin
sequentially by default int max(int a, int b);
• Defined once, called over and over int main()
• Functions can call other functions {
int x, y, mx;
– Goes and executes that collection of code cin >> x >> y; // say "6 103"
then returns to continue the current function
/* Code for main */
• Compute max of two integers 6
z = max(x,4);
Each call causes the program to pause the
cout << z << endl;
current function, go to the called function 103
cout << max(x, y) << endl;
and execute its code with the given
arguments then return to where the calling return 0;
}
function left off,
• Return value is substituted in place of the // Definition
int max(int a, int b)
function call {
if(a > b) return a;
else return b;
}
6
Anatomy of a function
void printMenu()
Parameter Passing
• Formal parameters, a and b #include <iostream>
using namespace std;
– Type of data they expect
int max(int a, int b) Formals
– Names that will be used internal to the function to {
refer to the values (placeholders/aliases) for if(a > b)
actuals return a;
else
• Actual parameters return b;
– Actual values input to the function by the caller }
– A copy is made and given to function
int main()
x {
int x=6, z;
Actuals 6 4 z = max(x,4); Actuals
cout << “Max is “ << z << endl;
z = max(125, 199); Actuals
Formals a b 6 cout << “Max is “ << z << endl;
return 0;
max() }
return val
Parameter Passing
#include <iostream>
• Formal parameters, n1 and n2 using namespace std;
– Type of data they expect double avg(int n1, int n2)
{
– Names that will be used internal to the function to
double sum = n1 + n2;
refer to the values return sum/2.0;
• Actual parameters }
– Actual values input to the function code by the copy copy
int main()
caller
{
– A copy is made and given to function
int x=6, y = 9; double z;
x y
z = avg(x,y);
avg()
return val
Parameter Passing
#include <iostream>
• Formal parameters, n1 and n2 using namespace std;
– Type of data they expect void inc(int x)
{
– Names that will be used internal to the function to
x = x+1;
refer to the values
}
• Actual parameters
– Actual values input to the function code by the int main( )
caller {
– A copy is made and given to function int x=6;
x 6
inc(x);
cout << “X is “ << x << endl;
Actuals 6 return 0;
}
Formals x
inc()
x 7
Each type is a "different" shape (int = triangle, double = square,
char = circle). Only a value of that type can "fit" as a parameter..
10
Example Functions 1
Function Signature/Prototype
double calcInterest(double amt, int yrs, double rate);
int main()
{
double amount, r;
cin >> amount >> r;
Example Functions 2
Function Signature/Prototype
bool checkLogin(string exp_pwd);
#include <iostream>
main using namespace std;
// prototype
pass bool checkLogin(string exp_pwd);
int main()
{
string pass = "Open123!"; // secret password
bool valid;
Example Functions 3
Function Signature/Prototype
void validateLogin(string exp_pwd);
#include <iostream>
main using namespace std;
// prototype
pass void validateLogin(string exp_pwd);
int main()
{
string pass = "Open123!"; // secret password
bool valid;
Example Functions 4
Function Signature/Prototype
bool genCoinFlip();
#include <iostream>
main #include <cstdlib>
using namespace std;
// prototype
bool genCoinFlip();
int main()
{
bool heads;
heads = genCoinFlip();
if(heads == true) { cout << "Heads!" << endl; }
else { cout << "Tails!" << endl; }
return 0;
}
genCoinFlip heads
bool genCoinFlip()
{
int r = rand(); // Generate random integer
return r%2;
}
14
Program Decomposition
• C is a procedural language
– Main unit of code organization, problem decomposition, and
abstraction is the “function” or “procedure”
– Function or procedure is a unit of code that
• Can be called from other locations in the program
• Can be passed variable inputs (a.k.a. arguments or parameters)
• Can return a value to the code that called it
• C++ is considered an “object-oriented” language (really just
adds objected-oriented constructs to C)
– Main unit of organization, problem decomposition, and abstraction is
an object (collection of code & associated data)
15
Exercise
• To decompose a program into functions, try
listing the verbs or tasks that are performed to
solve the problem
– Model a card game as a series of tasks/procedures…
• shuffle(), deal(), cut(), drawCard(), checkIfWon(), …
– A database representing a social network
• addUser(), addFriend(), updateStatus(), etc.
16
Function Prototypes
int main()
{
• The compiler (g++/clang++) needs to double area1,area2,area3;
area3 = triangle_area(5.0,3.5);
“know” about a function before it can X }
handle a call to that function
double triangle_area(double b, double h)
• The compiler will scan a file from top {
return 0.5 * b * h;
to bottom }
types for the parameters but not their double triangle_area(double b, double h)
names (ends with a ‘;’) {
return 0.5 * b * h;
– Prototype is used to check that you are }
calling it with the correct syntax (i.e. Compiler sees a prototype and can check the
parameter data types & return type) syntax of any following call and expects the
(like a menu @ a restaurant) definition later.
17
Practice
• Remove Factors
– Websheets Exercise: cpp/functions/remove_factor
• Draw an ASCII square on the screen
– Websheets Exercise: cpp/functions/draw_square
• Practice overloading a function
– Websheets Exercise: cpp/functions/overload
20
Memory Organization
• 32-bit address range (0x0 – 0xffffffff) Address
0
• Code usually sits at lower addresses Code
…
allocated during program execution (i.e. dynamically
at run-time) based on the needs of the program
Heap
• System stack (memory for each function instance that
is alive)
– Local variables
…
– Return link (where to return)
– etc.
… Stack
(area for
data local to
fffffffc a function)
Memory (RAM)
24
Local Variables
// Computes rectangle area,
// prints it, & returns it
• Any variable declared inside a function is int print_rect_area(int, int);
void print_answer(int);
called a “local” variable int main()
• It lives in the stack area for that function {
int wid = 8, len = 5, a;
• It dies when the function returns }
a = print_rect_area(wid,len);
Scope
• Global variables live as long as the program is running
• Variables declared in a block { … } are ‘local’ to that block
– { … } of a function
– { … } of a loop, if statement, etc.
– Die/deallocated when the program reaches the end of the block…don’t
try to access them intentionally or unintentionally after they are ‘out of
scope’/deallocated
– Actual parameters act as local variables and die when the function ends
• When variables share the same name the closest declaration will
be used by default
28
Scope Example
#include <iostream> Address
• Globals live as long as using namespace std; 0
the program is running int x = 5; Code
Memory (RAM)
29
PASS BY VALUE
30
Pass-by-Value
• Passing an argument to a function makes a copy of
the argument
• It is like e-mailing an attached document
– You still have the original on your PC
– The recipient has a copy which he can modify but it will
not be reflected in your version
• Communication is essentially one-way
– Caller communicates arguments to callee, but callee
cannot communicate back because he is working on
copies…
– The only communication back to the caller is via a return
value.
31
Pass by Value
void decrement_it(int);
int main()
• Notice that actual arguments are different {
memory locations/variables than the formal int a, y = 3;
decrement_it(y);
arguments cout << “y = “ << y << endl;
return 0;
• When arguments are passed a copy of the }
System
Memory Data for decrement_it
(RAM) (y=3 then 2) and return link
Data
Data forfor
mainmain
(a, (a,
y=3)y=3) and
and return
return
linklink
Another Exercise
#include <iostream>
• Guessing game #include <cstdlib>
#include <ctime>
– Number guessing game
int main()
[0-19]…indicate higher or lower until {
they guess correctly or stop after 5 srand(time(0));
unsuccessful guesses int secretNum = rand() % 20;
// Now create a game that
– Use a function to perform one // lets the user try to guess
// the random number in up to
"turn" of the game and return // 5 guesses
whether the user guessed the
number correctly }