Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
105 views

Unit4 Functions C++ PDF

The document discusses C/C++ functions. It defines a function as a black box that takes inputs and returns an output without specifying how it achieves the task internally. A function has a name, parameters, and a return type. The function signature or prototype specifies these aspects. User-defined functions are defined with code within curly braces and can call other functions. When a function is called, the code is executed sequentially before returning to the calling function. Parameters are passed by value where copies are made of the actual parameters.

Uploaded by

dejire
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
105 views

Unit4 Functions C++ PDF

The document discusses C/C++ functions. It defines a function as a black box that takes inputs and returns an output without specifying how it achieves the task internally. A function has a name, parameters, and a return type. The function signature or prototype specifies these aspects. User-defined functions are defined with code within curly braces and can call other functions. When a function is called, the code is executed sequentially before returning to the calling function. Parameters are passed by value where copies are made of the actual parameters.

Uploaded by

dejire
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 33

1

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

– 0 or 1 return (output) values


• We only specify the type
• The signature (or prototype) of a function
specifies these aspects so others know
how to "call" the function
4

User Defined Functions


#include <iostream>
• We can define our own functions using namespace std;
// prototype / declaratoin
• Good practice is to "declare" your int max(int a, int b);
function by placing the prototype int main()
(signature) at the top of your code {
int x, y, mx;
• "Define" the function (actual code cin >> x >> y;
implementation) anywhere by
/* Code for main */
placing the code in { }
• As shown it is defined but never
used (no one actually "calls" the }
max function)
// Definition
int max(int a, int b)
{
• At most 1 return value if(a > b)
– void = 0 return values return a; // immediately stops max
else
• Return value is substituted at the return b; // immediately stops max
site of the function call and used in }
the larger expression
5

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()

• Return type (any valid C type)


{
cout << “Welcome to ABC 2.0:” << endl;
cout << “===================" << endl;
– void, int, double, char, etc. cout << “ Enter an option:" << endl;
cout << “ 1.) Start" << endl;
– void means return nothing cout << “ 2.) Continue" << endl;
cout << “ 3.) End\n" << endl;
• Function name }
bool only_2_3_factors(int num)
– Any valid identifier {
while(num % 2 == 0){
• Input arguments inside () ...
}
– Act like a locally declared ...
if(num==1)
variable return 1;
return 0;
• Code }

– In {…} double triangle_area(double b, double h)


{
• Non-void functions must have double area = 0.5 * b * h;
return area;
1 or more return statements }

– First 'return' executed


immediately quits function
7

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

Each type is a "different" shape (int = triangle, double = square,


char = circle). Only a value of that type can "fit" as a parameter..
8

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

Actuals 6 9 cout << “AVG is “ << z << endl;


z = avg(x, 2);
cout << “AVG is “ << z << endl;
Formals n1 n2 7.5 return 0;
}

avg()
return val

Each type is a "different" shape (int = triangle, double = square,


char = circle). Only a value of that type can "fit" as a parameter..
9

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

main #include <iostream>


#include <cmath>
using namespace std;
amount 30 r
// prototype
double calcInterest(double amt, int yrs, double rate);

int main()
{
double amount, r;
cin >> amount >> r;

double interest = calcInterest(amount, 30, r);


amt yrs rate cout << "Interest: " << interest << endl;
return 0;
}
calcInterest interest
double calcInterest(double amt, int yrs, double rate)
{
return amt * pow(rate/12, 12*yrs);
}
11

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;

cout << "Enter your password: " << endl;


exp_pwd valid = checkLogin(pass);
if(valid == true) { cout << "Success!" << endl; }
return 0;
}
checkLogin valid
bool checkLogin(string exp_pwd)
{
string actual;
cin >> actual;
return actual == exp_pwd;
}
12

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;

cout << "Enter your password: " << endl;


exp_pwd validateLogin(pass);
return 0;
}

checkLogin void validateLogin(string exp_pwd)


{
string actual;
cin >> actual;
if(actual == exp_pwd){ cout << "Success!" << endl; }
else { cout << "Incorrect!" << endl; }
}
13

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 }

• If it encounters a call to a function Compiler encounters a call to triangle_area()


before the actual function code it will before it has seen its definition (Error!)
complain…[Compile error] double triangle_area(double, double);
int main()
• …Unless a prototype (“declaration”) {
double area1,area2,area3;
for the function is defined earlier area3 = triangle_area(5.0,3.5);
• A prototype only needs to include data }

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

The Need For Prototypes


• How would you order the functions in the program
on the left if you did NOT want to use prototypes?
• You can't!
int main() int f1(int);
{ int f2(int);
cout << f1(5) << endl;
} int main()
{
int f1(int x) cout << f1(5) << endl;
{ }
return f2(x*x);
} int f1(int x)
{
int f2(int y) return f2(x*x);
{ }
if(x > 10000) return;
else f1(y); int f2(int y)
} {
if(x > 10000) return;
else f1(y);
}
18

Overloading: A Function's Signature


• What makes up a signature (uniqueness) of a function
– name
– number and type of arguments
• No two functions are allowed to have the same signature; the
following 6 functions are unique and allowable…
– int f1(int), int f1(double), int f1(int, double)
– void f1(char), double f1(), int f1(int, char)
• Return type does not make a function unique
– int f1() and double f1() are not unique and thus not
allowable
• Two functions with the same name are said to be
"overloaded"
– int max(int, int); double max(double, double);
19

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

FUNCTION CALL SEQUENCING


21

Function Call Sequencing


void print_char_10_times(char);
void print_char(char);
• Functions can call other functions
int main()
and so on… {
char c = '*';
• When a function is called the calling print_char_10_times(c);
y = 5; ...
function is suspended (frozen) along return 0;
with all its data and control jumps to }

the start of the called function


void print_char_10_times(char c)
• When the called function returns {
for(int i=0; i < 10; i++) {
execution resumes in the calling print_char(c);
function }
return;
• Each function has its own set of }

variables and “scope”


void print_char(char c)
– Scope refers to the {
visibility/accessibility of a variable cout << c << endl;
}
from the current place of execution
22

More Function Call Sequencing


// Computes rectangle area,
// prints it, & returns it
• As one function calls another, they int print_rect_area(int, int);
void print_answer(int);
execute in a last-in, first-out fashion int main()
(i.e. the last one called is the first {
int wid = 8, len = 5, a;
one to finish & return) a = print_rect_area(wid,len);
– Just like in the cafeteria the last plate put }

on the top of the stack is the first one to


int print_rect_area(int w, int l)
be pulled off (always access the top item) {
• How does the computer actually int ans = w * l;
print_answer(ans);
track where to return to when a return ans;
}
function completes
void print_answer(int area)
{
cout << “Area is “ << area;
cout << endl;
}
23

Memory Organization
• 32-bit address range (0x0 – 0xffffffff) Address
0
• Code usually sits at lower addresses Code

• Global variables/data somewhere after code …

• Heap: Area of memory that can be allocated and de- Globals


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

More Function Call Sequencing


// Computes rectangle area,
// prints it, & returns it
• Computer maintains a “stack” of function data int print_rect_area(int, int);
void print_answer(int);
and info in memory (i.e. RAM) int main()
– Each time a function is called, the computer {
int wid = 8, len = 5, a;
allocates memory for that function on the top of a = print_rect_area(wid,len);
the stack and a link for where to return }

– When a function returns that memory is de- int print_rect_area(int w, int l)


allocated and control is returned to the function {
int ans = w * l;
now on top print_answer(ans);
Code
Code for
for all functions
all functions return ans;
Address 0x0000000
}

Data for print_answer (area) void print_answer(int area)


System and return link to print_rect {
cout << “Area is “ << area;
Memory Data for print_rect (w,l,ans)
cout << endl;
(RAM) and return link to main }
Data for main (wid,len,a) and
return link to OS

System stack area


0xffff ffff
25

LOCAL VARIABLES & SCOPE


26

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

int print_rect_area(int w, int l)


{
int ans = w * l;
print_answer(ans);
Code
Code for
for all functions
all functions return ans;
Address 0x0000000
}

Data for print_answer (area) void print_answer(int area)


System and return link to print_rect {
cout << “Area is “ << area;
Memory Data for print_rect (w,l,ans)
cout << endl;
(RAM) and return link to main }
Data for main (wid,len,a) and
return link to OS

System stack area


0xffff ffff
27

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

• Variables declared in a int main()


{

block { … } live as long as int a, x = 8, y = 3; Globals


x=5
cout << “x = “ << x << endl;
the block has not for(int i=0; i < 10; i++){
int j = 1; …
completed j = 2*i + 1;
– { … } of a function a += j;
}
– { … } of a loop, if statement, Heap
a = doit(y);
etc. cout << “a=“ << a ;
• When variables share the cout << “y=“ << y << endl;
cout << “glob. x” << ::x << endl;
same name the closest } …
declaration will be used by …

default int doit(int x)


doit:
{
(x= 3=>2)
x--; main:
return x; (a=,main:
x=8,y=3)
} fffffffc (a=121,
(a=2,
(a,
( ( x=8,y=3)
x=8,y=3)
i,x=8,y=3)
j ))

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 }

actual argument value (e.g. 3) is placed in the void decrement_it(int y)


{
formal parameter (x) y--;
}
• The value of y cannot be changed by any other
function (remember it is local)
Code
Code for
for all functions
all functions
Address 0x0000000

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

System stack area


0xffff ffff
32

Nested Call Practice


• Find characters in a string then use that
function to find how many vowels are in a
string
– Websheets Exercise: cpp/functions/vowels
33

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 }

• bool guessAndCheck(int secretNum);

Ch. 5, PE 16 of D.S. Malik, C++ Programming, 6th Ed.

You might also like