0% found this document useful (0 votes)
7 views

C++ Functions

This document provides a summary of functions in C++. It discusses the basics of functions including how they divide programs into smaller pieces and facilitate design, implementation, and maintenance. There are two types of functions - member functions and global functions. Global functions do not belong to a class. The main function is a global function. When a function is called, a new stack frame is created and pushed onto the call stack. Each frame stores the function parameters, local variables, and return address. When the function returns, its frame is popped off the stack.

Uploaded by

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

C++ Functions

This document provides a summary of functions in C++. It discusses the basics of functions including how they divide programs into smaller pieces and facilitate design, implementation, and maintenance. There are two types of functions - member functions and global functions. Global functions do not belong to a class. The main function is a global function. When a function is called, a new stack frame is created and pushed onto the call stack. Each frame stores the function parameters, local variables, and return address. When the function returns, its frame is popped off the stack.

Uploaded by

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

Functions

CS 201

This slide set covers the basics of


C++ functions. Please read
Chapter 6 (6.1 - 6.17) from your
Deitel & Deitel book.
1
Introduction
● Divide and conquer technique
○ Construct a large program from small, simple pieces (e.g., components)

● Functions
○ Facilitate the design, implementation, operation, and maintenance of large programs

● C++ supports two types of functions


○ Member functions
○ Global functions

2
Global functions
● Do not belong to a particular class

● In C++, main is a global function

● Many functions in C++ Standard Library header files are global


○ For example, sqrt in the <cmath> header file
■ Call it as sqrt( 900.0 )

● You can also write your own global functions


(although it is not an object-oriented programming)

3
Functions
signature

You can overload functions


int myFunction( int a, double b ); by using the same function
name with different
prototype signatures.

signature

int myClass::myFunction( int a, double b );

prototype 4
Example:
Write a global function which takes two int parameters and returns their largest

#include <iostream>
using namespace std;

int findMax( int, int );

int main() {
int larger = findMax( 42, 16 );
cout << "The larger of 42 and 16 is " << larger << endl;
return 0;
}

int findMax( int x, int y ) {


if ( x > y )
return x;
else
return y;
}
5
Function call stack
● Also called the program execution stack or run-time stack
● Call stack supports the function call / return mechanism
○ Functions use allocated storage called
frame on the call stack static local
variables
○ Function parameters and its non-static
(automatic) local variables are stored within global
the function’s frame variables
○ Storage size of a parameter or a variable is
determined by its data type LATER
dynamic
Return address After
allocations
you learn
(by new)
Frame Parameters pointers
(activation
record) Local variables

Call Stack Other memory


6
sections
Function call stack
● Each time a function makes a call to another function
○ A new stack frame (also known as an activation record) for the new
function call is created and pushed onto the top of the stack
○ Default argument passing initializes the function parameters by copying the
value of the function call arguments (known as pass-by-value)
○ Return address that the called function needs to return to in its caller is also
maintained

● Each time a function returns


○ Stack frame for this function call is popped out from the stack
○ Control is transferred to the return address in the popped stack frame
Return address
● Stack overflow Frame Parameters
○ Error that occurs when there are too many function calls such (activation
that the necessary space for their frames exceeds the size of the record) Local variables
call stack (due to memory limitations)
Call Stack 7
How is this program executed? (Example for call stack & frames)
#include <iostream>
using namespace std;

int square( int ); //prototype

int main() {
int a = 10;
cout << a << " squared: "
<< square( a ) << endl;
return 0;
}

// returns the square of an integer


int square( int x ) {
return x * x;
}
© 2006 Pearson Education, Inc. All rights reserved.

Output Function call stack after the operating system


10 squared: 100 invokes main to execute the application 8
How is this program executed? (Example for call stack & frames)
#include <iostream>
using namespace std;

int square( int ); //prototype

int main() {
int a = 10;
cout << a << " squared: "
<< square( a ) << endl;
return 0;
}

// returns the square of an integer


int square( int x ) {
return x * x;
}
© 2006 Pearson Education, Inc. All rights reserved.

Output Function call stack after main invokes the


10 squared: 100 function square to perform the calculation 9
How is this program executed? (Example for call stack & frames)
#include <iostream>
using namespace std;

int square( int ); //prototype

int main() {
int a = 10;
cout << a << " squared: "
<< square( a ) << endl;
return 0;
}

// returns the square of an integer


int square( int x ) {
return x * x;
}
© 2006 Pearson Education, Inc. All rights reserved.

Output Function call stack after the function square


10 squared: 100 returns to main 10
Parameter passing in C++
● Two ways to pass arguments to functions

● Pass-by-value
○ Copy of the argument’s value is passed to the called function
○ Changes to the copy do not affect the original argument’s value in the caller
■ Prevents accidental side effects of functions
○ Default parameter passing

● Pass-by-reference
○ Gives called function the ability to access and modify the caller’s argument data directly

11
Pass-by-reference
● Reference variable int count;
○ An alias, which is another name for an already existing variable int& no = count;
○ & is placed after the variable type count = 4;
○ A reference should be initialized with a variable. Then, this variable cout << no << endl;
may be referenced by either the variable name or the reference
name

● Reference parameter void bar( int& id ) {


id = 10;
○ An alias for its corresponding argument in a function call
}
○ & is placed after the parameter type in the function prototype and
void foo ( ) {
the function header int a = 5;
○ Data types of the argument and the reference parameter SHOULD bar( a );
be the same cout << a << endl;
○ Parameter name in the body of the called function actually refers to }
the original variable in the calling function Read as “id is a reference to an
12
int” (from right to left)
Pass-by-value and pass-by-reference for primitive types
#include <iostream> #include <iostream>
using namespace std; using namespace std;
void nextIntByValue( int ); void nextIntByReference( int& );
int main() { int main() {
int x = 10; int x = 20;
nextIntByValue( x ); nextIntByReference( x );
cout << x << endl; cout << x << endl;
return 0; return 0;
} }
void nextIntByValue( int y ) { void nextIntByReference( int& y ) {
y++; y++;
} }

nextIntByValue uses nextIntByReference uses


pass-by-value pass-by-reference
What is the output of this program? What is the output of this program? 13
Pass-by-value and pass-by-reference for objects
#include <iostream> void nextStudentIdByValue( Student s ) {
using namespace std; int x = s.getId();
class Student { x++;
public: s.setId( x );
Student( int i = 0 ); }
void setId( int i );
int main() {
int getId();
private:
Student s1( 20 );
int id; nextStudentIdByValue( s1 );
}; cout << s1.getId() << endl;
Student::Student( int i ) { return 0;
setId(i); }
}
void Student::setId( int i ) { nextStudentIdByValue uses
id = i;
}
pass-by-value
int Student::getId( ) {
return id;
What is the output of this program?
}
BE CAREFUL: That is different than Java!!! 14
Pass-by-value and pass-by-reference for objects
#include <iostream> void nextStudentIdByReference( Student& s ) {
using namespace std; int x = s.getId();
class Student { x++;
public: s.setId( x );
Student( int i = 0 ); }
void setId( int i );
int main() {
int getId();
private:
Student s2( 40 );
int id; nextStudentIdByReference( s2 );
}; cout << s2.getId() << endl;
Student::Student( int i ) { return 0;
setId(i); }
}
void Student::setId( int i ) { nextStudentIdByReference uses
id = i;
}
pass-by-reference
int Student::getId( ) {
return id;
What is the output of this program?
}
15
Remarks on parameter passing in C++
● Disadvantage of pass-by-value
○ If a large data item is passed, copying that data can take a considerable amount of execution
time and memory space

● Advantages of pass-by-reference
○ When used for objects, it is good for performance reasons, because it eliminates the
pass-by-value overhead of copying large amounts of data
○ A useful way to be able to return more than one value

● Disadvantages of pass-by-reference
○ Pass-by-reference can weaken security since the called function can corrupt the caller’s data
○ Hard to tell from the function call if it is pass-by-reference (so cannot tell if it will be modified)
○ Cannot pass a literal value (or an expression or a variable of a different but compatible type) to
a reference type parameter (e.g., nextIntByRef( 4 ) is an invalid call)

16
Principle of least privilege
● Functions should not be given the capability to modify its parameters unless
it is absolutely necessary

● const qualifier is used to enforce this principle when defining parameters


○ void example( const int x, const GradeBook& G);
■ const int x // parameter x cannot be modified in the function
■ const GradeBook& G // parameter G is a constant reference to an object, so it
cannot be modified in the function and it cannot call a non-const member function

● Using the principle of least privilege to properly design software


○ can greatly reduce debugging time
○ can greatly reduce improper side effects
○ can make a program easier to modify and maintain

17
Principle of least privilege
#include <iostream> void foo( const Book& B ){
using namespace std; // B is a constant reference, thus it CANNOT change
class Book{ // a data member or call a non-const member function
public:
void setNo( int i ); // THREE STATEMENTS BELOW LEAD TO COMPILE-TIME ERRORS
int getNo( ) const; // B.publicNo = 10;
void displayNo( ); // B.setNo(20);
int publicNo; // B.displayNo();
private: cout << B.getNo() << endl;
int no; }
}; int main() {
void Book::setNo( int n ){ Book A;
no = n; foo( A );
} return 0;
int Book::getNo( ) const{ }
return no;
} For passing large objects, use a constant reference parameter
void Book::displayNo( ){ to simulate the appearance and security of pass-by-value and
cout << no << endl;
avoid the overhead of passing a copy of the large object. 18
}
Exercise (returning more than one value):
Write a global function which takes two int parameters and computes and returns the sum of the
inputs and the product of the inputs. The input parameters should not be modified. Use the principle
of least privilege.

void computeSumProduct( ? x, ? y, ? sum, ? product ){


sum = x + y;
product = x * y;
}
int main(){
int s, p, c = 10;
double r, t = 3.2;
computeSumProduct( ?, ?, ?, ? );

return 0;
} 19
Exercise (returning more than one value):
Write a global function which takes two int parameters and computes and returns the sum of the
inputs and the product of the inputs. The input parameters should not be modified. Use the principle
of least privilege.

void computeSumProduct( const int x, const int y, int& sum, int& product ){
sum = x + y;
product = x * y;
}
int main(){
int s, p, c = 10;
double r, t = 3.2;
computeSumProduct( c, t, s, p );

// cannot pass a literal value, or an expression, or a variable of a different type to


// a reference parameter (although it is ok to pass them to a pass-by-value parameter)
// computeSumProduct( c + 4, 15, s + 5, r ); // COMPILE-TIME ERROR

// order of evaluation of a function’s arguments is not specified by the C++ standard


// thus, different compilers can evaluate function arguments in different orders
computeSumProduct( c++, c++, s, p ); // MAY YIELD A WARNING

return 0;
}
20
Storage class, scope, and linkage
● Each identifier has several attributes
○ Name, type, size, and value
○ Also storage class, scope, and linkage

■ Identifier’s storage class determines the period during which that identifier exists in
memory (automatic and static variables)

■ Identifier’s scope determines where the identifier can be referenced in a program

■ Identifier’s linkage determines whether an identifier is known only in the source file
where it is declared or across multiple files that are compiled, then linked together (use
of the extern specifier)

21
Storage class (automatic variables)
What is the output?
● Only a local variable and a function void foo() {
parameter can be of the automatic storage int k = 10;
cout << k << endl;
class k++;
if ( k > 5 ) {
○ Created when the program execution enters the
int a = 50;
block in which it is defined
cout << a << endl;
○ Exists while the block is active k++;
}
○ Destroyed when the execution exits the block
cout << k << endl;
}
● Default declaration (can also be declared int main() {
int k = 20;
with keyword auto) cout << k << endl;
k++;
foo();
cout << k << endl;
Automatic variables are stored in the call stack return 0;
} 22
Storage class (static local variables)
What is the output?
● A local variable declared with static void g1() {
int a = 4;
○ Exists from the point at which the program begins
cout << a << endl;
execution
a++;
○ Initialized only once when its declaration is first }
encountered void g2() {
static int b = 4;
○ Retains its value when the function (in which this cout << b << endl;
local variable is declared) returns to its caller b++;
■ Next time this function is called, it contains }
the value it had at the end of this function’s int main() {
last call g1();
g1();
■ However, known only in this function (that is,
g2();
its scope is only this function) g2();
// cout << a; compile-time error
// cout << b; compile-time error
Static local variables are stored in the data section return 0;
} 23
Storage class (static global variables)
What is the output?
● A global variable is static by its definition int k = 4;
void h1() {
(keyword static is not used) cout << k << endl;
○ Defined by placing variable declaration outside any k = 7;
}
class or function definition
void h2() {
○ Created at the beginning of the program cout << k << endl;
k++;
○ Retains its value throughout the program execution }
○ Can be referenced by any function that follows its void h3() {
int k = 1;
declaration cout << k << endl;
Do not use them as an alternative to parameter passing k = 20;
}
(do not use them if it is not that necessary!!!)
int main() {
cout << k << endl;
h1(); cout << k << endl;
h2(); cout << k << endl;
h3(); cout << k << endl;
Global variables are also stored in the data section
return 0;
} 24
Scope (file scope)
● Scope of an identifier: a portion of the program where it can be referenced
● Identifiers (global variables, global function definitions/prototypes) declared
outside a function or a class all have the file scope
○ These identifiers can be referenced in all functions from the point at which they are declared
until the end of the file

double a1 = 3.14; prog.cpp // now every function prog.cpp


void f1(){ // can reference a1 (but not a2) // can reference every global variable
// can call f1 (but not f2 or f3) // can call every global function
} double a1 = 3.14;
void f2(){ // can reference a1 (but not a2) int a2 = 4;
// can call f1 and f2 (but not f3) void f1();
} void f2();
int a2 = 4; void f3();
void f3(){ // can reference a1 and a2
// can call f1, f2 and f3 void f1(){ ... }
} void f2(){ ... }
void f3(){ ... }
25
Scope (block scope)
● Scope of an identifier: a portion of the program where it can be referenced
● Local variables and function parameters have the block scope
○ Block scope begins at the identifier’s declaration
○ Block scope ends at the terminating } of the block in which the identifier is declared
○ Storage duration of the identifier does not affect its scope

What is the output?


void foo( int a, double b ) { a, b, c, d, and S1
int c; have this block scope int main() {
static double d = 3.14; (their scopes begin int a = 5, b = 4;
Student S1; at their declaration if (b > 0){
int a = 2;
if (d > 1) { An identifier in an outer cout << a << endl;
int e; e and S2 block is “hidden” when }
Student S2; have this a nested block has an cout << a << endl;
block scope
} identifier with the same return 0;
} name }
26
Overloaded functions
● These are the functions with the same name but a different signature
(different parameter lists)
● The compiler selects a proper function to execute based on the number,
types, and order of the arguments in a function call
● Commonly used to create several functions of the same name that
perform similar tasks, but on different data types

27
Function templates
● More compact and convenient form of overloading
○ Identical program logic and operations for each data type

● Function template definition


○ Written by the programmer only once
○ Essentially defines a whole family of overloaded functions
○ Defined by template < typename tname > or template < class tname >

● Function template specializations will automatically be generated by the


compiler to handle each type of call to the function template

28
Write a generic maximum function using a function template
main.cpp #ifndef __MAX_H max.h
#include <iostream>
#include <string> #define __MAX_H
using namespace std;
template < typename T >
#include "max.h" T maximum( T num1, T num2 ) {
if ( num1 > num2 )
int main() { return num1;
cout << "The maximum of 5 and 3: "; else
cout << maximum( 5, 3 ) << endl; return num2;
}
double a = 4.5; #endif
cout << "The maximum of a and 5.6: ";
cout << maximum( a, 5.6 ) << endl; Output
The maximum of 5 and 3:5
string s1 = "Hello", s2 = "World";
The maximum of a and 5.6: 5.6
cout << "The maximum of s1 and s2: ";
The maximum of s1 and s2: World
cout << maximum( s1, s2 ) << endl;

// compile time error The compiler generates a separate function


// cout << maximum( a, 5 ) << endl;
return 0;
definition for each call with arguments of a
} different type
29
C++ Standard Library header files
● The C++ Standard Library is divided into many portions, each with its
own header file
○ Each header “instructs” the compiler on how to interface with its corresponding portion
of the library

● Each header file contains


○ Prototypes for the related functions belonging to the portion of the library that the
header file corresponds to
○ Definitions of various class types and constants necessary for its functions and for the
client code

30
31
©1992-2014 by Pearson Education, Inc. All Rights Reserved.
©1992-2014 by Pearson Education, Inc. All Rights Reserved.
32
©1992-2014 by Pearson Education, Inc. All Rights Reserved.
33
Math functions
● The <cmath> header file provides a
collection of functions that enable you to
perform common mathematical calculations

● All functions in the <cmath> header file are


global functions—therefore, each is called
simply by specifying the name of the
function followed by parentheses containing
the function’s arguments

34
©1992-2014 by Pearson Education, Inc. All Rights Reserved.

You might also like