SlideShare a Scribd company logo
Functions in C++
Outline














Introduction
Standard library in a programming language
C++ Header files
String and character related fuctions
Mathematical functions
Console I/O operations
Other fuctions
Fuction statistics
Types of functions
Function definition
Accesing a function
Returning from a function
Scope rules
Introduction
Functions allow to structure programs in segments
of code to perform individual tasks.
In C++, a function is a group of statements that is
given a name, and which can be called from
some point of the program. The most common
syntax to define a function is:
type name ( parameter1, parameter2, ...) {
statements }
Standard Library in a
Programming Language
 The C++ standard consists of two parts: the core language

and the C++ Standard Library; which C++ programmers
expect on every major implementation of C++, it
includes vectors, lists, maps,algorithms
(find, for_each, binary_search, random_shuffle, etc.), sets,
queues, stacks, arrays, tuples, input/output facilities
(iostream; reading from the console input, reading/writing
from files),smart pointers for automatic memory
management, regular expression support, multi-threading
library, atomics support (allowing a variable to be read or
written to be at most one thread at a time without any
external synchronisation), time utilities
(measurement, getting current time, etc.), a system for
converting error reporting that doesn't use
C++ exceptions into C++ exceptions, a random number
generator and a slightly modified version of the C standard
library (to make it comply with the C++ type system).
 A large part of the C++ library is based on the STL .This provides

useful tools as containers (for example vectors and lists), iterators to
provide these containers with array-like access andalgorithms to
perform operations such as searching and sorting. Furthermore
(multi)maps (associative arrays) and (multi)sets are provided, all of
which export compatible interfaces. Therefore it is possible, using
templates, to write generic algorithms that work with any container
or on any sequence defined by iterators. As in C, the features of
the library are accessed by using the#include directive to include
a standard header. C++ provides 105 standard headers, of which 27
are deprecated.
 The standard incorporates the STL was originally designed
by Alexander Stepanov, who experimented with generic algorithms
and containers for many years. When he started with C++, he finally
found a language where it was possible to create generic algorithms
(e.g., STL sort) that perform even better than, for example, the C
standard library qsort, thanks to C++ features like using inlining and
compile-time binding instead of function pointers. The standard
does not refer to it as "STL", as it is merely a part of the standard
library, but the term is still widely used to distinguish it from the rest
of the standard library (input/output
streams, internationalization, diagnostics, the C library subset, etc.).
 Most C++ compilers, and all major ones, provide a standards
conforming implementation of the C++ standard library.
Function Definition











The general form of a C++ function definition is as follows:
return_type function_name( parameter list ) { body of the function }A
C++ function definition consists of a function header and a function
body. Here are all the parts of a function:
Return Type: A function may return a value. The return_type is the data
type of the value the function returns. Some functions perform the
desired operations without returning a value. In this case, the
return_type is the keyword void.
Function Name: This is the actual name of the function. The function
name and the parameter list together constitute the function signature.
Parameters: A parameter is like a placeholder. When a function is
invoked, you pass a value to the parameter. This value is referred to as
actual parameter or argument. The parameter list refers to the
type, order, and number of the parameters of a function. Parameters are
optional; that is, a function may contain no parameters.
Function Body: The function body contains a collection of statements
that define what the function does.
Function Declarations:
 A function declaration tells the compiler about a function





name and how to call the function. The actual body of the
function can be defined separately.
A function declaration has the following parts:
return_type function_name( parameter list );For the above
defined function max(), following is the function
declaration:
int max(int num1, int num2);Parameter names are not
importan in function declaration only their type is
required, so following is also valid declaration:
int max(int, int);Function declaration is required when you
define a function in one source file and you call that
function in another file. In such case, you should declare the
function at the top of the file calling the function.
Calling a Function:
 While creating a C++ function, you give a definition

of what the function has to do. To use a function, you
will have to call or invoke that function.
 When a program calls a function, program control is
transferred to the called function. A called function
performs defined task and when its return statement
is executed or when its function-ending closing
brace is reached, it returns program control back to
the main program.
 To call a function, you simply need to pass the
required parameters along with function name, and
if function returns a value, then you can store
returned value.
Function Arguments:













If a function is to use arguments, it must declare variables that accept the values
of the arguments. These variables are called the formal parameters of the
function.
The formal parameters behave like other local variables inside the function and
are created upon entry into the function and destroyed upon exit.
While calling a function, there are two ways that arguments can be passed to a
function:
Call TypeDescription
Call by valueThis method copies the actual value of an argument into the formal
parameter of the function. In this case, changes made to the parameter inside
the function have no effect on the argument.
Call by pointerThis method copies the address of an argument into the formal
parameter. Inside the function, the address is used to access the actual argument
used in the call. This means that changes made to the parameter affect the
argument.
Call by referenceThis method copies the reference of an argument into the
formal parameter. Inside the function, the reference is used to access the actual
argument used in the call. This means that changes made to the parameter
affect the argument.By default, C++ uses call by value to pass arguments.
In general, this means that code within a function cannot alter the arguments
used to call the function and above mentioned example while calling max()
function used the same method.
Default Values for Parameters:
 When you define a function, you can specify a
default value for each of the last parameters.
This value will be used if the corresponding

argument is left blank when calling to the
function.
 This is done by using the assignment operator
and assigning values for the arguments in the
function definition. If a value for that parameter
is not passed when the function is called, the
default given value is used, but if a value is
specified, this default value is ignored and the
passed value is used instead.
About Functions in C++
 Functions invoked by a function–call-statement which consist

of it’s name and information it needs (arguments)
 Boss To Worker Analogy
 A Boss (the calling/caller function) asks a worker (the called
function) to perform a task and return result when it is done.
Boss
Main
Worker
Worker

Worker

Function A

Function B

Worker

Function B1

Worker

Function B2

Function Z
Note: usual main( ) Calls other
functions, but other functions can
call each other
Function Calling
• Functions

called by writing

functionName (argument);
or

functionName(argument1, argument2, …);
• Example
cout << sqrt( 900.0 );
• sqrt (square root) function

• The preceding statement would print 30
• All functions in math library return a double


-

Function Arguments can be:
Constant
sqrt(9);
Variable
sqrt(x);
Expression
sqrt( x*9 + y) ;
sqrt( sqrt(x) ) ;
Function Calling
• Calling/invoking a function
– sqrt(x);
– Parentheses an operator used to call function
• Pass argument x
• Function gets its own copy of arguments
– After finished, passes back result
Function Name

cout<< sqrt(9);

Output

argument

3

Parentheses used to enclose argument(s)
Math Library Functions Revisited
Method
ceil( x )

exp( x )

Description
rounds x to the smallest integer
not less than x
trigonometric cosine of x
(x in radians)
exponential function ex

fabs( x )

absolute value of x

floor( x )

log( x )

rounds x to the largest integer
not greater than x
remainder of x/y as a floatingpoint number
natural logarithm of x (base e)

log10( x )

logarithm of x (base 10)

pow( x, y )

x raised to power y (xy)

sin( x )

trigonometric sine of x
(x in radians)
square root of x

cos( x )

fmod( x, y )

sqrt( x )
tan( x )

trigonometric tangent of x
(x in radians)
Fig. 3.2 Math library functions.

Example
ceil( 9.2 ) is 10.0
ceil( -9.8 ) is -9.0
cos( 0.0 ) is 1.0
exp( 1.0 ) is 2.71828
exp( 2.0 ) is 7.38906
fabs( 5.1 ) is 5.1
fabs( 0.0 ) is 0.0
fabs( -8.76 ) is 8.76
floor( 9.2 ) is 9.0
floor( -9.8 ) is -10.0
fmod( 13.657, 2.333 ) is 1.992
log( 2.718282 ) is 1.0
log( 7.389056 ) is 2.0
log10( 10.0 ) is 1.0
log10( 100.0 ) is 2.0
pow( 2, 7 ) is 128
pow( 9, .5 ) is 3
sin( 0.0 ) is 0
sqrt( 900.0 ) is 30.0
sqrt( 9.0 ) is 3.0
tan( 0.0 ) is 0
Function Definition
• Example function
int square( int y )
{
return y * y;
}

• return keyword
– Returns data, and control goes to function’s caller
• If no data to return, use return;

– Function ends when reaches right brace
• Control goes to caller

• Functions cannot be defined inside other
functions
// Creating and using a programmer-defined function.
#include <iostream.h>
int square( int );

// function prototype

Function prototype: specifies
data types of arguments and
return values. square
expects an int, and returns
an int.

int main()
{
// loop 10 times and calculate and output
// square of x each time
for ( int x = 1; x <= 10; x++ )
cout << square( x ) << " "; // function call

Parentheses () cause function to be called.
When done, it returns the result.

cout << endl;
return 0;

// indicates successful termination

} // end main

// square function definition returns square of an integer
int square( int y ) // y is a copy of argument to function
{
Definition
return y * y;
// returns square of y as an int

of square. y is a
copy of the argument passed.
Returns y * y, or y squared.

} // end function square

1

4

9

16

25

36

49

64

81

100
compute square and cube of numbers [1..10] using functions
#include<iostream.h>
int square(int); // prototype
int cube(int);
// prototype
main()
{ int i;
for (int i=1;i<=10;i++){
cout<< i<< “square=“ << square(i) << endl;
cout<< i<< “cube=“
<<cube(i) << endl;
} // end for
return 0;
} // end main function
int square(int y) //function definition
{
return y*y; // returned Result
}
int cube(int y) //function definition
{
return y*y*y; // returned Result
}

Output
1 square=1
1 cube=1
2 square=4
2 cube=8
.
.
.
.
10 square=100
10 cube=1000
Function Prototypes


Function prototype contains







Function name
Parameters (number and data type)
Return type (void if returns nothing)
Only needed if function definition after function call

Prototype must match function definition


Function prototype
double maximum( double, double, double );



Definition
double maximum( double x, double y, double
z )
{
…
}
void Function takes arguments
If the Function does not RETURN result, it is called void
Function
#include<iostream.h>
void add2Nums(int,int);
main()
{
int a, b;
cout<<“enter tow Number:”;
cin >>a >> b;
add2Nums(a, b)
return 0;
}
void add2Nums(int x, int y)
{
cout<< x<< “+” << y << “=“ << x+y;
}
void Function take no arguments
If the function Does Not Take Arguments specify this with EMPTY-LIST OR
write void inside
#include<iostream.h>
void funA();
void funB(void)
main()
Will be the same
{
funA();
in all cases
funB();
return 0;
}
void funA()
{
cout << “Function-A takes no arqumentsn”;
}
void funB()
{
cout << “Also Function-B takes No argumentsn”;
}
Remarks on Functions


Local variables





Parameters




Known only in the function in which they are defined
All variables declared inside a function are local variables

Local variables passed to function when called (passingparameters)

Variables defined outside and before function main:




Called global variables
Can be accessible and used anywhere in the entire
program
Remarks on Functions


Omitting the type of returned result defaults to int, but
omitting a non-integer type is a Syntax Error



If a Global variable defined again as a local variable in a
function, then the Local-definition overrides the Global
defining



Function prototype, function definition, and function call
must be consistent in:
1- Number of arguments
2- Type of those arguments
3-Order of those arguments
Local vs Global Variables
#include<iostream.h>
int x,y; //Global Variables
int add2(int, int); //prototype
main()
{ int s;
x = 11;
y = 22;
cout << “global x=” << x << endl;
cout << “Global y=” << y << endl;
s = add2(x, y);
cout << x << “+” << y << “=“ << s;
cout<<endl;
cout<<“n---end of output---n”;
return 0;
}
int add2(int x1,int y1)
{ int x; //local variables
x=44;
cout << “nLocal x=” << x << endl;
return x1+y1;
}

global x=11
global y=22
Local x=44
11+22=33
---end of output---
Finding Errors in Function Code
int sum(int x, int y)
{
int result;
result = x+y;
}
this function must return an integer value as indicated in the
header definition (return result;) should be added
---------------------------------------------------------------------------------------int sum (int n)
{ if (n==0)
return 0;
else
n+sum(n-1);
}
the result of n+sum(n-1) is not returned; sum returns an
improper result, the else part should be written as:else return n+sum(n-1);
Finding Errors in Function Code
void f(float a);
{
float a;
cout<<a<<endl;
}


; found after function definition header.

redefining the parameter a in the function
void f(float a)
{
float a2 = a + 8.9;
cout <<a2<<endl;
}

Finding Errors in Function Code
void product(void)
{
int a, b, c, result;
cout << “enter three integers:”;
cin >> a >> b >> c;
result = a*b*c;
cout << “Result is” << result;
return result;
}

According to the definition it should not return a value , but in the block
(body) it did & this is WRONG.

 Remove return Result;
Function Call Methods
Call by value



•

A copy of the value is passed

Call by reference



•

The caller passes the address of the value



Call by value



Up to this point all the calls we have seen are call-by-value, a copy
of the value (known) is passed from the caller-function to the calledfunction
Any change to the copy does not affect the original value in the
caller function
Advantages, prevents side effect, resulting in reliable software




Function Call Methods


Call By Reference



We introduce reference-parameter, to perform call by reference. The caller
gives the called function the ability to directly access the caller’s value, and
to modify it.
A reference parameter is an alias for it’s corresponding argument, it is stated
in c++ by “flow the parameter’s type” in the function prototype by an
ampersand(&) also in the function definition-header.
Advantage: performance issue





void

function_name (type &);// prototype

main()
{
---------}
void function_name(type &parameter_name)
Function Call Example
#include<iostream.h>
int squareVal(int); //prototype call by value function
void squareRef(int &); // prototype call by –reference function
int main()
{ int x=2; z=4;
cout<< “x=“ << x << “before calling squareVal”;
cout << “n” << squareVal(x) << “n”; // call by value
cout<< “x=“ << x << “After returning”
cout<< “z=“ << z << “before calling squareRef”;
squareRef(z); // call by reference
cout<< “z=“ << z<< “After returning squareRef”
return 0;
x=2 before calling squareVal
}
4
int squareVal(int a)
x=2 after returning
{
z=4 before calling squareRef
return a*=a; // caller’s argument not modified
z=16 after returning squareRef
}
void squarRef(int &cRef)
{
cRef *= cRef; // caller’s argument modified
}
Random Number Generator


rand function generates an integer between 0 and RAND-



MAX(~32767) a symbolic constant defined in <stdlib.h>
You may use modulus operator (%) to generate numbers within a
specifically range with rand.

//generate 10 random numbers open-range
int x;
for( int i=0; i<=10; i++){
x=rand();
cout<<x<<“ “;
}

------------------------------------------------------//generate 10 integers between 0……..49
int x;
for( int i=0; i<10; i++){
x=rand()%50;
cout<<x<<“ “;
}
Random Number Generator
//generate 10 integers between 5…15
int x;
for ( int i=1; i<=10; i++){
x= rand()%11 + 5;
cout<<x<<“ “;
}
------------------------------------

//generate 100 number as simulation of rolling a
dice
int x;
for (int i=1; i<=100; i++){
x= rand%6 + 1;
cout<<x<<“ “;
}
Random Number Generator




the rand( ) function will generate the same set of
random numbers each time you run the program .
To force NEW set of random numbers with each new
run use the randomizing process
Randomizing is accomplished with the standard library
function srand(unsigned integer); which needs a
header file <stdlib.h>

Explanation of signed and unsigned integers:
 int is stored in at least two-bytes of memory and can
have positive & negative values
 unsigned int also stored in at least two-bytes of
memory but it can have only positive values 0…..65535
Randomizing with srand
#include<iostream.h>
#include<iomanip.h>
#include<stdlib.h>
int main()
{
int i;
unsigned num;
// we will enter a different number each time we run
cin>>num;
srand(num);
for(i=1; i<=5; i++)
cout<<setw(10)<< 1+rand()%6;
return 0;
}

Output for Multiple Runs
19
18
3
0
3

6
6
1
1
1

1
1
2
5
2

1
5
5
5
5

4
1
6
3
6

2
4
2
5
3

1
4
4
5
4

Different-set of Random
numbers
without srand
#include<iostream.h>
#include<iomanip.h>
#include<stdlib.h>

int main()
{
int i;
for(i=1; i<=5; i++)
cout<<setw(10)<< 1+rand()%6;
return 0;
}

Output for Multiple Runs
5
5
5
5
6

3
3
3
3
5

3
3
3
3
3

5
5
5
5
3

4
4
4
4
5

2
2
2
2
4

Same set of numbers for
each run
Function Overloading


Function overloading
Functions with same name and different parameters
 Should perform similar tasks


 I.e., function to square ints and function to square floats
int square( int x) {return x * x;}
float square(float x) { return x * x; }


A call-time c++ complier selects the proper function by
examining the number, type and order of the parameters
C++ Variables
• A variable is a place in memory that has
–
–
–
–

A name or identifier (e.g. income, taxes, etc.)
A data type (e.g. int, double, char, etc.)
A size (number of bytes)
A scope (the part of the program code that can use it)
• Global variables – all functions can see it and using it
• Local variables – only the function that declare local variables see
and use these variables

– A life time (the duration of its existence)
• Global variables can live as long as the program is executed
• Local variables are lived only when the functions that define these
variables are executed

36
I. Using Global Variables
#include <iostream.h>
int x = 0;
void f1() { x++; }
void f2() { x+=4; f1(); }
void main()
{
f2();
cout << x << endl;
}

37
I. Using Global Variables
#include <iostream.h>
int x = 0;
void f1() { x++; }
void f2() { x+=4; f1(); }
void main()
{
f2();
cout << x << endl;
}

x

0

38
I. Using Global Variables
#include <iostream.h>
int x = 0;
void f1() { x++; }
void f2() { x+=4; f1(); }
void main()
{
f2();
cout << x << endl;
}

x

1

0

void main()
{
f2();
cout << x << endl ;
}
39
I. Using Global Variables
#include <iostream.h>
int x = 0;
void f1() { x++; }
void f2() { x+=4; f1(); }
void main()
{
f2();
cout << x << endl;
}

x

4
0

2

void f2()
{
x += 4;
f1();
}

1

void main()
{
f2();
cout << x << endl ;
}
40
I. Using Global Variables
#include <iostream.h>
int x = 0;
void f1() { x++; }
void f2() { x+=4; f1(); }
void main()
{
f2();
cout << x << endl;
}

x

4

3

1

5
4
void f1()
{
x++;
}
void f2()
{
x += 4;
f1();
}
void main()
{
f2();
cout << x << endl ;
}
41
I. Using Global Variables
#include <iostream.h>
int x = 0;
void f1() { x++; }
void f2() { x+=4; f1(); }
void main()
{
f2();
cout << x << endl;
}

x

5

3

1

5
4
void f1()
{
x++;
}
void f2()
{
x += 4;
f1();
}
void main()
{
f2();
cout << x << endl;
}
42
I. Using Global Variables
#include <iostream.h>
int x = 0;
void f1() { x++; }
void f2() { x+=4; f1(); }
void main()
{
f2();
cout << x << endl;
}

x

6

1

5
4

void f2()
{
x += 4;
f1();
}
void main()
{
f2();
cout << x << endl;
}
43
I. Using Global Variables
#include <iostream.h>
int x = 0;
void f1() { x++; }
void f2() { x+=4; f1(); }
void main()
{
f2();
cout << x << endl;
}

x

7

5
4

void main()
{
f2();
cout << x << endl;
}
44
I. Using Global Variables
#include <iostream.h>
int x = 0;
void f1() { x++; }
void f2() { x+=4; f1(); }
void main()
{
f2();
cout << x << endl;
}

x

8

5
4

void main()
{
f2();
cout << x << endl;
}
45
I. Using Global Variables
#include <iostream.h>
int x = 0;
void f1() { x++; }
void f2() { x+=4; f1(); }
void main()
{
f2();
cout << x << endl;
}
46
What is Bad About Using
Global Vairables?
• Not safe!
– If two or more programmers are working together in a
program, one of them may change the value stored in the
global variable without telling the others who may depend
in their calculation on the old stored value!

• Against The Principle of Information Hiding!
– Exposing the global variables to all functions is against
the principle of information hiding since this gives all
functions the freedom to change the values stored in the
global variables at any time (unsafe!)

47
Local Variables
• Local variables are declared inside the function
body and exist as long as the function is running
and destroyed when the function exit
• You have to initialize the local variable before using
it
• If a function defines a local variable and there was a
global variable with the same name, the function
uses its local variable instead of using the global
variable

48
Example of Defining and Using Global
and Local Variables
#include <iostream.h>
int x; // Global variable
Void fun(); // function signature
void main()
{
x = 4;
fun();
cout << x << endl;
}
void fun()
{
int x = 10; // Local variable
cout << x << endl;
}
49
Example of Defining and Using Global
and Local Variables
#include <iostream.h>
int x; // Global variable
Void fun(); // function signature

x

0

Global variables are
automatically initialized to 0

void main()
{
x = 4;
fun();
cout << x << endl;
}
void fun()
{
int x = 10; // Local variable
cout << x << endl;
}
50
Example of Defining and Using Global
and Local Variables
#include <iostream.h>
int x; // Global variable
Void fun(); // function signature

x

0

void main()
{
x = 4;
fun();
cout << x << endl;
}
void fun()
{
int x = 10; // Local variable
cout << x << endl;
}

1

void main()
{
x = 4;
fun();
cout << x << endl;
}

51
Example of Defining and Using Global
and Local Variables
#include <iostream.h>
int x; // Global variable
Void fun(); // function signature
void main()
{
x = 4;
fun();
cout << x << endl;
}
void fun()
{
int x = 10; // Local variable
cout << x << endl;
}

4

x

void fun()
x

????

{
int x = 10;
cout << x << endl;

3
}

2

void main()
{
x = 4;
fun();
cout << x << endl;
}

52
Example of Defining and Using Global
and Local Variables
#include <iostream.h>
int x; // Global variable
Void fun(); // function signature
void main()
{
x = 4;
fun();
cout << x << endl;
}
void fun()
{
int x = 10; // Local variable
cout << x << endl;
}

4

x

void fun()
x

10

{
int x = 10;
cout << x << endl;

3
}

2

void main()
{
x = 4;
fun();
cout << x << endl;
}

53
Example of Defining and Using
Global and Local Variables
#include <iostream.h>
int x; // Global variable
Void fun(); // function signature
void main()
{
x = 4;
fun();
cout << x << endl;
}
void fun()
{
int x = 10; // Local variable
cout << x << endl;
}

4

x

void fun()
x

10

{
int x = 10;
cout << x << endl;

4

}

2

void main()
{
x = 4;
fun();
cout << x << endl;
}

54
Example of Defining and Using
Global and Local Variables
#include <iostream.h>
int x; // Global variable
Void fun(); // function signature
void main()
{
x = 4;
fun();
cout << x << endl;
}
void fun()
{
int x = 10; // Local variable
cout << x << endl;
}

4

x

void fun()
x

10

{
int x = 10;
cout << x << endl;
5

2

}
void main()
{
x = 4;
fun();
cout << x << endl;
}

55
Example of Defining and Using
Global and Local Variables
#include <iostream.h>
int x; // Global variable
Void fun(); // function signature

x

4

void main()
{
x = 4;
fun();
cout << x << endl;
}
void fun()
{
int x = 10; // Local variable
cout << x << endl;
}
6

void main()
{
x = 4;
fun();
cout << x << endl;
}

56
Example of Defining and Using
Global and Local Variables
#include <iostream.h>
int x; // Global variable
Void fun(); // function signature

x

4

void main()
{
x = 4;
fun();
cout << x << endl;
}
void fun()
{
int x = 10; // Local variable
cout << x << endl;
}

7

void main()
{
x = 4;
fun();
cout << x << endl;
}

57
II. Using Parameters
• Function Parameters come in three
flavors:
– Value parameters – which copy the
values of the function arguments
– Reference parameters – which refer to
the function arguments by other local
names and have the ability to change
the values of the referenced arguments
– Constant reference parameters – similar
to the reference parameters but cannot
58
change the values of the referenced
Value Parameters
• This is what we use to declare in the function signature or
function header, e.g.

int max (int x, int y);
– 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 copies to x and y respectively

• Once the value parameters accepted copies of the
corresponding arguments data, they act as local
variables!
59
Example of Using Value Parameters
and Global Variables
#include <iostream.h>
int x; // Global variable
void fun(int x)
{
cout << x << endl;
x=x+5;
}
void main()
{
x = 4;
fun(x/2+1);
cout << x << endl;
}

x

1

0

void main()
{
x = 4;
fun(x/2+1);
cout << x << endl;
}

60
Example of Using Value Parameters
and Global Variables
#include <iostream.h>
int x; // Global variable
void fun(int x)
{
cout << x << endl;
x=x+5;
}
void main()
{
x = 4;
fun(x/2+1);
cout << x << endl;
}

x

3

2

4

void fun(int x
)
{
cout << x << endl;
x=x+5;
}
void main()
{
3
x = 4;
fun(x/2+1);
cout << x << endl;
}

61
Example of Using Value Parameters
and Global Variables
#include <iostream.h>
int x; // Global variable
void fun(int x)
{
cout << x << endl;
x=x+5;
}
void main()
{
x = 4;
fun(x/2+1);
cout << x << endl;
}

x

4

2

4

void fun(int x 3 )
8
{
cout << x << endl;
x=x+5;
}
void main()
{
x = 4;
fun(x/2+1);
cout << x << endl;
}

62
Example of Using Value Parameters
and Global Variables
#include <iostream.h>
int x; // Global variable
void fun(int x)
{
cout << x << endl;
x=x+5;
}
void main()
{
x = 4;
fun(x/2+1);
cout << x << endl;
}

x

5

2

4

void fun(int x 3 )
8
{
cout << x << endl;
x=x+5;
}
void main()
{
x = 4;
fun(x/2+1);
cout << x << endl;
}

63
Example of Using Value Parameters
and Global Variables
#include <iostream.h>
int x; // Global variable
void fun(int x)
{
cout << x << endl;
x=x+5;
}
void main()
{
x = 4;
fun(x/2+1);
cout << x << endl;
}

x

6

4

void main()
{
x = 4;
fun(x/2+1);
cout << x << endl;
}

64
Example of Using Value Parameters
and Global Variables
#include <iostream.h>
int x; // Global variable
void fun(int x)
{
cout << x << endl;
x=x+5;
}
void main()
{
x = 4;
fun(x/2+1);
cout << x << endl;
}

x

7

4

void main()
{
x = 4;
fun(x/2+1);
cout << x << endl;
}

65
Reference Parameters
• As we saw in the last example, any changes in the
value parameters don’t affect the original function
arguments
• 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);
66
Example of Reference Parameters
#include <iostream.h>
void fun(int &y)
{
cout << y << endl;
y=y+5;
}
void main()
{
int x = 4; // Local variable
fun(x);
cout << x << endl;
}

1

void main()
{
4
?
int x = 4;
fun(x);
cout << x << endl;
}

x

67
Example of Reference Parameters
#include <iostream.h>
void fun(int &y)
{
cout << y << endl;
y=y+5;
}
void main()
{
int x = 4; // Local variable
fun(x);
cout << x << endl;
}

3

2

void fun( int & y
{
cout<<y<<endl;
y=y+5;
}
void main()
{
4
?
int x = 4;
fun(x);
cout << x << endl;
}

)

x

68
Example of Reference Parameters
#include <iostream.h>
void fun(int &y)
{
cout << y << endl;
y=y+5;
}
void main()
{
int x = 4; // Local variable
fun(x);
cout << x << endl;
}

4

2

void fun( int & y
{
cout<<y<<endl;
y=y+5;
9
}
void main()
{
4
?
int x = 4;
fun(x);
cout << x << endl;
}

)

x

69
Example of Reference Parameters
#include <iostream.h>
void fun(int &y)
{
cout << y << endl;
y=y+5;
}
void main()
{
int x = 4; // Local variable
fun(x);
cout << x << endl;
}

5

2

void fun( int & y
{
cout<<y<<endl;
y=y+5;
}
void main()
{
9
?
int x = 4;
fun(x);
cout << x << endl;
}

)

x

70
Example of Reference Parameters
#include <iostream.h>
void fun(int &y)
{
cout << y << endl;
y=y+5;
}
void main()
{
int x = 4; // Local variable
fun(x);
cout << x << endl;
}

6

void main()
{
9
?
int x = 4;
fun(x);
cout << x << endl;
}

x

71
Example of Reference Parameters
#include <iostream.h>
void fun(int &y)
{
cout << y << endl;
y=y+5;
}
void main()
{
int x = 4; // Local variable
fun(x);
cout << x << endl;
}
7

void main()
{
9
?
int x = 4;
fun(x);
cout << x << endl;
}

x

72
Constant Reference Parameters
• Constant reference parameters are used under
the following two conditions:
– The passed data are so big and you want to save
time and computer memory
– The passed data will not be changed or updated in
the function body

• For example
void report (const string & prompt);
• The only valid arguments accepted by reference
parameters and constant reference parameters
are variable names
– It is a syntax error to pass constant values or
expressions to the (const) reference parameters
73
Header Files
• Header files
– Contain function prototypes for library
functions
– <stdlib.h> , <math.h> , etc
– Load with #include <filename>
#include <math.h>
• Custom header files
– Create file with functions
– Save as filename.h
– Load in other files with #include
Scope Rules
• File scope
– Identifier defined outside function, known in
all functions
– Used for global variables, function
definitions, function prototypes
• Function scope
– Can only be referenced inside a function
body
– Used only for labels (start:, case:
, etc.)
Scope Rules
• Block scope
– Identifier declared inside a block
• Block scope begins at declaration, ends
at right brace
– Used for variables, function parameters
(local variables of function)
– Outer blocks "hidden" from inner blocks if
there is a variable with the same name in
the inner block
• Function prototype scope
Thank You

More Related Content

PPT
C++ Functions
PPT
C++ Function
PPT
C++ functions
PPTX
C and C++ functions
PPTX
C++ programming function
PPT
C++ functions presentation by DHEERAJ KATARIA
PPT
16717 functions in C++
 
PPT
Functions in c++
C++ Functions
C++ Function
C++ functions
C and C++ functions
C++ programming function
C++ functions presentation by DHEERAJ KATARIA
16717 functions in C++
 
Functions in c++

What's hot (18)

PPT
Lecture#6 functions in c++
PPT
Functions in C++
PPT
C++ functions
ODP
Function
PPT
Function overloading(C++)
PPT
Functions in C++
PPTX
functions of C++
PDF
Functions
PPTX
PDF
Functions in C++
PPT
Functions in C++
PPTX
Parameter passing to_functions_in_c
PPTX
Functions in c++
PPTX
Learning C++ - Functions in C++ 3
PPTX
Call by value or call by reference in C++
PPTX
Function in c++
PPTX
Function in c program
PDF
03 function overloading
Lecture#6 functions in c++
Functions in C++
C++ functions
Function
Function overloading(C++)
Functions in C++
functions of C++
Functions
Functions in C++
Functions in C++
Parameter passing to_functions_in_c
Functions in c++
Learning C++ - Functions in C++ 3
Call by value or call by reference in C++
Function in c++
Function in c program
03 function overloading
Ad

Viewers also liked (20)

PPTX
C++ theory
DOCX
Designing the application
PPT
Part 3-functions
PDF
Chapter 10 Library Function
PPT
Csc1100 lecture06 ch06_pt2
PPT
Lec 45.46- virtual.functions
PPTX
Vocabulary: Ana & Paloma
PPTX
Project: Ana & Paloma
PPTX
writting skills
DOCX
Type header file in c++ and its function
PPT
C++ functions
PPTX
The Essential School's Guide to Adaptive Learning
PDF
Character building
PDF
Basic communication skills
PPT
C++ programming
PDF
Object Oriented Program
PDF
C++ arrays part2
PPS
Inheritance
C++ theory
Designing the application
Part 3-functions
Chapter 10 Library Function
Csc1100 lecture06 ch06_pt2
Lec 45.46- virtual.functions
Vocabulary: Ana & Paloma
Project: Ana & Paloma
writting skills
Type header file in c++ and its function
C++ functions
The Essential School's Guide to Adaptive Learning
Character building
Basic communication skills
C++ programming
Object Oriented Program
C++ arrays part2
Inheritance
Ad

Similar to Functions in C++ (20)

PPTX
Functions in C++
PPT
Ch4 functions
PDF
Cpp functions
PPTX
Functions in Python Programming Language
PPTX
User defined function in C.pptx
PDF
1.6 Function.pdf
DOC
Functions
PPT
python slides introduction interrupt.ppt
PPTX
Python Functions.pptx
PPTX
Python Functions.pptx
PDF
All chapters C++ - Copy.pdfyttttttttttttttttttttttttttttt
PDF
programlama fonksiyonlar c++ hjhjghjv jg
PPT
Py-Slides-3 difficultpythoncoursefforbeginners.ppt
PPT
Powerpoint presentation for Python Functions
PPTX
UNIT-02-pythonfunctions python function using detehdjsjehhdjejdhdjdjdjddjdhdhhd
PPTX
c & c++ logic building concepts practice.pptx
PPTX
Unit_5Functionspptx__2022_12_27_10_47_17 (1).pptx
PPT
Python programming variables and comment
PPTX
Lecture_5_-_Functions_in_C_Detailed.pptx
PPTX
Functions in c language
Functions in C++
Ch4 functions
Cpp functions
Functions in Python Programming Language
User defined function in C.pptx
1.6 Function.pdf
Functions
python slides introduction interrupt.ppt
Python Functions.pptx
Python Functions.pptx
All chapters C++ - Copy.pdfyttttttttttttttttttttttttttttt
programlama fonksiyonlar c++ hjhjghjv jg
Py-Slides-3 difficultpythoncoursefforbeginners.ppt
Powerpoint presentation for Python Functions
UNIT-02-pythonfunctions python function using detehdjsjehhdjejdhdjdjdjddjdhdhhd
c & c++ logic building concepts practice.pptx
Unit_5Functionspptx__2022_12_27_10_47_17 (1).pptx
Python programming variables and comment
Lecture_5_-_Functions_in_C_Detailed.pptx
Functions in c language

Recently uploaded (20)

PDF
Abdominal Access Techniques with Prof. Dr. R K Mishra
PDF
Complications of Minimal Access Surgery at WLH
PPTX
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
PDF
Mark Klimek Lecture Notes_240423 revision books _173037.pdf
PPTX
Week 4 Term 3 Study Techniques revisited.pptx
PPTX
BOWEL ELIMINATION FACTORS AFFECTING AND TYPES
PPTX
Final Presentation General Medicine 03-08-2024.pptx
PDF
Origin of periodic table-Mendeleev’s Periodic-Modern Periodic table
PDF
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
PPTX
Renaissance Architecture: A Journey from Faith to Humanism
PDF
O7-L3 Supply Chain Operations - ICLT Program
PPTX
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
PDF
Classroom Observation Tools for Teachers
PPTX
master seminar digital applications in india
PDF
STATICS OF THE RIGID BODIES Hibbelers.pdf
PDF
O5-L3 Freight Transport Ops (International) V1.pdf
PDF
Supply Chain Operations Speaking Notes -ICLT Program
PDF
Business Ethics Teaching Materials for college
PPTX
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
PPTX
human mycosis Human fungal infections are called human mycosis..pptx
Abdominal Access Techniques with Prof. Dr. R K Mishra
Complications of Minimal Access Surgery at WLH
school management -TNTEU- B.Ed., Semester II Unit 1.pptx
Mark Klimek Lecture Notes_240423 revision books _173037.pdf
Week 4 Term 3 Study Techniques revisited.pptx
BOWEL ELIMINATION FACTORS AFFECTING AND TYPES
Final Presentation General Medicine 03-08-2024.pptx
Origin of periodic table-Mendeleev’s Periodic-Modern Periodic table
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
Renaissance Architecture: A Journey from Faith to Humanism
O7-L3 Supply Chain Operations - ICLT Program
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
Classroom Observation Tools for Teachers
master seminar digital applications in india
STATICS OF THE RIGID BODIES Hibbelers.pdf
O5-L3 Freight Transport Ops (International) V1.pdf
Supply Chain Operations Speaking Notes -ICLT Program
Business Ethics Teaching Materials for college
Introduction_to_Human_Anatomy_and_Physiology_for_B.Pharm.pptx
human mycosis Human fungal infections are called human mycosis..pptx

Functions in C++

  • 2. Outline              Introduction Standard library in a programming language C++ Header files String and character related fuctions Mathematical functions Console I/O operations Other fuctions Fuction statistics Types of functions Function definition Accesing a function Returning from a function Scope rules
  • 3. Introduction Functions allow to structure programs in segments of code to perform individual tasks. In C++, a function is a group of statements that is given a name, and which can be called from some point of the program. The most common syntax to define a function is: type name ( parameter1, parameter2, ...) { statements }
  • 4. Standard Library in a Programming Language  The C++ standard consists of two parts: the core language and the C++ Standard Library; which C++ programmers expect on every major implementation of C++, it includes vectors, lists, maps,algorithms (find, for_each, binary_search, random_shuffle, etc.), sets, queues, stacks, arrays, tuples, input/output facilities (iostream; reading from the console input, reading/writing from files),smart pointers for automatic memory management, regular expression support, multi-threading library, atomics support (allowing a variable to be read or written to be at most one thread at a time without any external synchronisation), time utilities (measurement, getting current time, etc.), a system for converting error reporting that doesn't use C++ exceptions into C++ exceptions, a random number generator and a slightly modified version of the C standard library (to make it comply with the C++ type system).
  • 5.  A large part of the C++ library is based on the STL .This provides useful tools as containers (for example vectors and lists), iterators to provide these containers with array-like access andalgorithms to perform operations such as searching and sorting. Furthermore (multi)maps (associative arrays) and (multi)sets are provided, all of which export compatible interfaces. Therefore it is possible, using templates, to write generic algorithms that work with any container or on any sequence defined by iterators. As in C, the features of the library are accessed by using the#include directive to include a standard header. C++ provides 105 standard headers, of which 27 are deprecated.  The standard incorporates the STL was originally designed by Alexander Stepanov, who experimented with generic algorithms and containers for many years. When he started with C++, he finally found a language where it was possible to create generic algorithms (e.g., STL sort) that perform even better than, for example, the C standard library qsort, thanks to C++ features like using inlining and compile-time binding instead of function pointers. The standard does not refer to it as "STL", as it is merely a part of the standard library, but the term is still widely used to distinguish it from the rest of the standard library (input/output streams, internationalization, diagnostics, the C library subset, etc.).  Most C++ compilers, and all major ones, provide a standards conforming implementation of the C++ standard library.
  • 6. Function Definition       The general form of a C++ function definition is as follows: return_type function_name( parameter list ) { body of the function }A C++ function definition consists of a function header and a function body. Here are all the parts of a function: Return Type: A function may return a value. The return_type is the data type of the value the function returns. Some functions perform the desired operations without returning a value. In this case, the return_type is the keyword void. Function Name: This is the actual name of the function. The function name and the parameter list together constitute the function signature. Parameters: A parameter is like a placeholder. When a function is invoked, you pass a value to the parameter. This value is referred to as actual parameter or argument. The parameter list refers to the type, order, and number of the parameters of a function. Parameters are optional; that is, a function may contain no parameters. Function Body: The function body contains a collection of statements that define what the function does.
  • 7. Function Declarations:  A function declaration tells the compiler about a function     name and how to call the function. The actual body of the function can be defined separately. A function declaration has the following parts: return_type function_name( parameter list );For the above defined function max(), following is the function declaration: int max(int num1, int num2);Parameter names are not importan in function declaration only their type is required, so following is also valid declaration: int max(int, int);Function declaration is required when you define a function in one source file and you call that function in another file. In such case, you should declare the function at the top of the file calling the function.
  • 8. Calling a Function:  While creating a C++ function, you give a definition of what the function has to do. To use a function, you will have to call or invoke that function.  When a program calls a function, program control is transferred to the called function. A called function performs defined task and when its return statement is executed or when its function-ending closing brace is reached, it returns program control back to the main program.  To call a function, you simply need to pass the required parameters along with function name, and if function returns a value, then you can store returned value.
  • 9. Function Arguments:         If a function is to use arguments, it must declare variables that accept the values of the arguments. These variables are called the formal parameters of the function. The formal parameters behave like other local variables inside the function and are created upon entry into the function and destroyed upon exit. While calling a function, there are two ways that arguments can be passed to a function: Call TypeDescription Call by valueThis method copies the actual value of an argument into the formal parameter of the function. In this case, changes made to the parameter inside the function have no effect on the argument. Call by pointerThis method copies the address of an argument into the formal parameter. Inside the function, the address is used to access the actual argument used in the call. This means that changes made to the parameter affect the argument. Call by referenceThis method copies the reference of an argument into the formal parameter. Inside the function, the reference is used to access the actual argument used in the call. This means that changes made to the parameter affect the argument.By default, C++ uses call by value to pass arguments. In general, this means that code within a function cannot alter the arguments used to call the function and above mentioned example while calling max() function used the same method.
  • 10. Default Values for Parameters:  When you define a function, you can specify a default value for each of the last parameters. This value will be used if the corresponding argument is left blank when calling to the function.  This is done by using the assignment operator and assigning values for the arguments in the function definition. If a value for that parameter is not passed when the function is called, the default given value is used, but if a value is specified, this default value is ignored and the passed value is used instead.
  • 11. About Functions in C++  Functions invoked by a function–call-statement which consist of it’s name and information it needs (arguments)  Boss To Worker Analogy  A Boss (the calling/caller function) asks a worker (the called function) to perform a task and return result when it is done. Boss Main Worker Worker Worker Function A Function B Worker Function B1 Worker Function B2 Function Z Note: usual main( ) Calls other functions, but other functions can call each other
  • 12. Function Calling • Functions called by writing functionName (argument); or functionName(argument1, argument2, …); • Example cout << sqrt( 900.0 ); • sqrt (square root) function • The preceding statement would print 30 • All functions in math library return a double  - Function Arguments can be: Constant sqrt(9); Variable sqrt(x); Expression sqrt( x*9 + y) ; sqrt( sqrt(x) ) ;
  • 13. Function Calling • Calling/invoking a function – sqrt(x); – Parentheses an operator used to call function • Pass argument x • Function gets its own copy of arguments – After finished, passes back result Function Name cout<< sqrt(9); Output argument 3 Parentheses used to enclose argument(s)
  • 14. Math Library Functions Revisited Method ceil( x ) exp( x ) Description rounds x to the smallest integer not less than x trigonometric cosine of x (x in radians) exponential function ex fabs( x ) absolute value of x floor( x ) log( x ) rounds x to the largest integer not greater than x remainder of x/y as a floatingpoint number natural logarithm of x (base e) log10( x ) logarithm of x (base 10) pow( x, y ) x raised to power y (xy) sin( x ) trigonometric sine of x (x in radians) square root of x cos( x ) fmod( x, y ) sqrt( x ) tan( x ) trigonometric tangent of x (x in radians) Fig. 3.2 Math library functions. Example ceil( 9.2 ) is 10.0 ceil( -9.8 ) is -9.0 cos( 0.0 ) is 1.0 exp( 1.0 ) is 2.71828 exp( 2.0 ) is 7.38906 fabs( 5.1 ) is 5.1 fabs( 0.0 ) is 0.0 fabs( -8.76 ) is 8.76 floor( 9.2 ) is 9.0 floor( -9.8 ) is -10.0 fmod( 13.657, 2.333 ) is 1.992 log( 2.718282 ) is 1.0 log( 7.389056 ) is 2.0 log10( 10.0 ) is 1.0 log10( 100.0 ) is 2.0 pow( 2, 7 ) is 128 pow( 9, .5 ) is 3 sin( 0.0 ) is 0 sqrt( 900.0 ) is 30.0 sqrt( 9.0 ) is 3.0 tan( 0.0 ) is 0
  • 15. Function Definition • Example function int square( int y ) { return y * y; } • return keyword – Returns data, and control goes to function’s caller • If no data to return, use return; – Function ends when reaches right brace • Control goes to caller • Functions cannot be defined inside other functions
  • 16. // Creating and using a programmer-defined function. #include <iostream.h> int square( int ); // function prototype Function prototype: specifies data types of arguments and return values. square expects an int, and returns an int. int main() { // loop 10 times and calculate and output // square of x each time for ( int x = 1; x <= 10; x++ ) cout << square( x ) << " "; // function call Parentheses () cause function to be called. When done, it returns the result. cout << endl; return 0; // indicates successful termination } // end main // square function definition returns square of an integer int square( int y ) // y is a copy of argument to function { Definition return y * y; // returns square of y as an int of square. y is a copy of the argument passed. Returns y * y, or y squared. } // end function square 1 4 9 16 25 36 49 64 81 100
  • 17. compute square and cube of numbers [1..10] using functions #include<iostream.h> int square(int); // prototype int cube(int); // prototype main() { int i; for (int i=1;i<=10;i++){ cout<< i<< “square=“ << square(i) << endl; cout<< i<< “cube=“ <<cube(i) << endl; } // end for return 0; } // end main function int square(int y) //function definition { return y*y; // returned Result } int cube(int y) //function definition { return y*y*y; // returned Result } Output 1 square=1 1 cube=1 2 square=4 2 cube=8 . . . . 10 square=100 10 cube=1000
  • 18. Function Prototypes  Function prototype contains      Function name Parameters (number and data type) Return type (void if returns nothing) Only needed if function definition after function call Prototype must match function definition  Function prototype double maximum( double, double, double );  Definition double maximum( double x, double y, double z ) { … }
  • 19. void Function takes arguments If the Function does not RETURN result, it is called void Function #include<iostream.h> void add2Nums(int,int); main() { int a, b; cout<<“enter tow Number:”; cin >>a >> b; add2Nums(a, b) return 0; } void add2Nums(int x, int y) { cout<< x<< “+” << y << “=“ << x+y; }
  • 20. void Function take no arguments If the function Does Not Take Arguments specify this with EMPTY-LIST OR write void inside #include<iostream.h> void funA(); void funB(void) main() Will be the same { funA(); in all cases funB(); return 0; } void funA() { cout << “Function-A takes no arqumentsn”; } void funB() { cout << “Also Function-B takes No argumentsn”; }
  • 21. Remarks on Functions  Local variables    Parameters   Known only in the function in which they are defined All variables declared inside a function are local variables Local variables passed to function when called (passingparameters) Variables defined outside and before function main:   Called global variables Can be accessible and used anywhere in the entire program
  • 22. Remarks on Functions  Omitting the type of returned result defaults to int, but omitting a non-integer type is a Syntax Error  If a Global variable defined again as a local variable in a function, then the Local-definition overrides the Global defining  Function prototype, function definition, and function call must be consistent in: 1- Number of arguments 2- Type of those arguments 3-Order of those arguments
  • 23. Local vs Global Variables #include<iostream.h> int x,y; //Global Variables int add2(int, int); //prototype main() { int s; x = 11; y = 22; cout << “global x=” << x << endl; cout << “Global y=” << y << endl; s = add2(x, y); cout << x << “+” << y << “=“ << s; cout<<endl; cout<<“n---end of output---n”; return 0; } int add2(int x1,int y1) { int x; //local variables x=44; cout << “nLocal x=” << x << endl; return x1+y1; } global x=11 global y=22 Local x=44 11+22=33 ---end of output---
  • 24. Finding Errors in Function Code int sum(int x, int y) { int result; result = x+y; } this function must return an integer value as indicated in the header definition (return result;) should be added ---------------------------------------------------------------------------------------int sum (int n) { if (n==0) return 0; else n+sum(n-1); } the result of n+sum(n-1) is not returned; sum returns an improper result, the else part should be written as:else return n+sum(n-1);
  • 25. Finding Errors in Function Code void f(float a); { float a; cout<<a<<endl; }  ; found after function definition header. redefining the parameter a in the function void f(float a) { float a2 = a + 8.9; cout <<a2<<endl; } 
  • 26. Finding Errors in Function Code void product(void) { int a, b, c, result; cout << “enter three integers:”; cin >> a >> b >> c; result = a*b*c; cout << “Result is” << result; return result; }  According to the definition it should not return a value , but in the block (body) it did & this is WRONG.   Remove return Result;
  • 27. Function Call Methods Call by value  • A copy of the value is passed Call by reference  • The caller passes the address of the value  Call by value  Up to this point all the calls we have seen are call-by-value, a copy of the value (known) is passed from the caller-function to the calledfunction Any change to the copy does not affect the original value in the caller function Advantages, prevents side effect, resulting in reliable software  
  • 28. Function Call Methods  Call By Reference  We introduce reference-parameter, to perform call by reference. The caller gives the called function the ability to directly access the caller’s value, and to modify it. A reference parameter is an alias for it’s corresponding argument, it is stated in c++ by “flow the parameter’s type” in the function prototype by an ampersand(&) also in the function definition-header. Advantage: performance issue   void function_name (type &);// prototype main() { ---------} void function_name(type &parameter_name)
  • 29. Function Call Example #include<iostream.h> int squareVal(int); //prototype call by value function void squareRef(int &); // prototype call by –reference function int main() { int x=2; z=4; cout<< “x=“ << x << “before calling squareVal”; cout << “n” << squareVal(x) << “n”; // call by value cout<< “x=“ << x << “After returning” cout<< “z=“ << z << “before calling squareRef”; squareRef(z); // call by reference cout<< “z=“ << z<< “After returning squareRef” return 0; x=2 before calling squareVal } 4 int squareVal(int a) x=2 after returning { z=4 before calling squareRef return a*=a; // caller’s argument not modified z=16 after returning squareRef } void squarRef(int &cRef) { cRef *= cRef; // caller’s argument modified }
  • 30. Random Number Generator  rand function generates an integer between 0 and RAND-  MAX(~32767) a symbolic constant defined in <stdlib.h> You may use modulus operator (%) to generate numbers within a specifically range with rand. //generate 10 random numbers open-range int x; for( int i=0; i<=10; i++){ x=rand(); cout<<x<<“ “; } ------------------------------------------------------//generate 10 integers between 0……..49 int x; for( int i=0; i<10; i++){ x=rand()%50; cout<<x<<“ “; }
  • 31. Random Number Generator //generate 10 integers between 5…15 int x; for ( int i=1; i<=10; i++){ x= rand()%11 + 5; cout<<x<<“ “; } ------------------------------------ //generate 100 number as simulation of rolling a dice int x; for (int i=1; i<=100; i++){ x= rand%6 + 1; cout<<x<<“ “; }
  • 32. Random Number Generator    the rand( ) function will generate the same set of random numbers each time you run the program . To force NEW set of random numbers with each new run use the randomizing process Randomizing is accomplished with the standard library function srand(unsigned integer); which needs a header file <stdlib.h> Explanation of signed and unsigned integers:  int is stored in at least two-bytes of memory and can have positive & negative values  unsigned int also stored in at least two-bytes of memory but it can have only positive values 0…..65535
  • 33. Randomizing with srand #include<iostream.h> #include<iomanip.h> #include<stdlib.h> int main() { int i; unsigned num; // we will enter a different number each time we run cin>>num; srand(num); for(i=1; i<=5; i++) cout<<setw(10)<< 1+rand()%6; return 0; } Output for Multiple Runs 19 18 3 0 3 6 6 1 1 1 1 1 2 5 2 1 5 5 5 5 4 1 6 3 6 2 4 2 5 3 1 4 4 5 4 Different-set of Random numbers
  • 34. without srand #include<iostream.h> #include<iomanip.h> #include<stdlib.h> int main() { int i; for(i=1; i<=5; i++) cout<<setw(10)<< 1+rand()%6; return 0; } Output for Multiple Runs 5 5 5 5 6 3 3 3 3 5 3 3 3 3 3 5 5 5 5 3 4 4 4 4 5 2 2 2 2 4 Same set of numbers for each run
  • 35. Function Overloading  Function overloading Functions with same name and different parameters  Should perform similar tasks   I.e., function to square ints and function to square floats int square( int x) {return x * x;} float square(float x) { return x * x; }  A call-time c++ complier selects the proper function by examining the number, type and order of the parameters
  • 36. C++ Variables • A variable is a place in memory that has – – – – A name or identifier (e.g. income, taxes, etc.) A data type (e.g. int, double, char, etc.) A size (number of bytes) A scope (the part of the program code that can use it) • Global variables – all functions can see it and using it • Local variables – only the function that declare local variables see and use these variables – A life time (the duration of its existence) • Global variables can live as long as the program is executed • Local variables are lived only when the functions that define these variables are executed 36
  • 37. I. Using Global Variables #include <iostream.h> int x = 0; void f1() { x++; } void f2() { x+=4; f1(); } void main() { f2(); cout << x << endl; } 37
  • 38. I. Using Global Variables #include <iostream.h> int x = 0; void f1() { x++; } void f2() { x+=4; f1(); } void main() { f2(); cout << x << endl; } x 0 38
  • 39. I. Using Global Variables #include <iostream.h> int x = 0; void f1() { x++; } void f2() { x+=4; f1(); } void main() { f2(); cout << x << endl; } x 1 0 void main() { f2(); cout << x << endl ; } 39
  • 40. I. Using Global Variables #include <iostream.h> int x = 0; void f1() { x++; } void f2() { x+=4; f1(); } void main() { f2(); cout << x << endl; } x 4 0 2 void f2() { x += 4; f1(); } 1 void main() { f2(); cout << x << endl ; } 40
  • 41. I. Using Global Variables #include <iostream.h> int x = 0; void f1() { x++; } void f2() { x+=4; f1(); } void main() { f2(); cout << x << endl; } x 4 3 1 5 4 void f1() { x++; } void f2() { x += 4; f1(); } void main() { f2(); cout << x << endl ; } 41
  • 42. I. Using Global Variables #include <iostream.h> int x = 0; void f1() { x++; } void f2() { x+=4; f1(); } void main() { f2(); cout << x << endl; } x 5 3 1 5 4 void f1() { x++; } void f2() { x += 4; f1(); } void main() { f2(); cout << x << endl; } 42
  • 43. I. Using Global Variables #include <iostream.h> int x = 0; void f1() { x++; } void f2() { x+=4; f1(); } void main() { f2(); cout << x << endl; } x 6 1 5 4 void f2() { x += 4; f1(); } void main() { f2(); cout << x << endl; } 43
  • 44. I. Using Global Variables #include <iostream.h> int x = 0; void f1() { x++; } void f2() { x+=4; f1(); } void main() { f2(); cout << x << endl; } x 7 5 4 void main() { f2(); cout << x << endl; } 44
  • 45. I. Using Global Variables #include <iostream.h> int x = 0; void f1() { x++; } void f2() { x+=4; f1(); } void main() { f2(); cout << x << endl; } x 8 5 4 void main() { f2(); cout << x << endl; } 45
  • 46. I. Using Global Variables #include <iostream.h> int x = 0; void f1() { x++; } void f2() { x+=4; f1(); } void main() { f2(); cout << x << endl; } 46
  • 47. What is Bad About Using Global Vairables? • Not safe! – If two or more programmers are working together in a program, one of them may change the value stored in the global variable without telling the others who may depend in their calculation on the old stored value! • Against The Principle of Information Hiding! – Exposing the global variables to all functions is against the principle of information hiding since this gives all functions the freedom to change the values stored in the global variables at any time (unsafe!) 47
  • 48. Local Variables • Local variables are declared inside the function body and exist as long as the function is running and destroyed when the function exit • You have to initialize the local variable before using it • If a function defines a local variable and there was a global variable with the same name, the function uses its local variable instead of using the global variable 48
  • 49. Example of Defining and Using Global and Local Variables #include <iostream.h> int x; // Global variable Void fun(); // function signature void main() { x = 4; fun(); cout << x << endl; } void fun() { int x = 10; // Local variable cout << x << endl; } 49
  • 50. Example of Defining and Using Global and Local Variables #include <iostream.h> int x; // Global variable Void fun(); // function signature x 0 Global variables are automatically initialized to 0 void main() { x = 4; fun(); cout << x << endl; } void fun() { int x = 10; // Local variable cout << x << endl; } 50
  • 51. Example of Defining and Using Global and Local Variables #include <iostream.h> int x; // Global variable Void fun(); // function signature x 0 void main() { x = 4; fun(); cout << x << endl; } void fun() { int x = 10; // Local variable cout << x << endl; } 1 void main() { x = 4; fun(); cout << x << endl; } 51
  • 52. Example of Defining and Using Global and Local Variables #include <iostream.h> int x; // Global variable Void fun(); // function signature void main() { x = 4; fun(); cout << x << endl; } void fun() { int x = 10; // Local variable cout << x << endl; } 4 x void fun() x ???? { int x = 10; cout << x << endl; 3 } 2 void main() { x = 4; fun(); cout << x << endl; } 52
  • 53. Example of Defining and Using Global and Local Variables #include <iostream.h> int x; // Global variable Void fun(); // function signature void main() { x = 4; fun(); cout << x << endl; } void fun() { int x = 10; // Local variable cout << x << endl; } 4 x void fun() x 10 { int x = 10; cout << x << endl; 3 } 2 void main() { x = 4; fun(); cout << x << endl; } 53
  • 54. Example of Defining and Using Global and Local Variables #include <iostream.h> int x; // Global variable Void fun(); // function signature void main() { x = 4; fun(); cout << x << endl; } void fun() { int x = 10; // Local variable cout << x << endl; } 4 x void fun() x 10 { int x = 10; cout << x << endl; 4 } 2 void main() { x = 4; fun(); cout << x << endl; } 54
  • 55. Example of Defining and Using Global and Local Variables #include <iostream.h> int x; // Global variable Void fun(); // function signature void main() { x = 4; fun(); cout << x << endl; } void fun() { int x = 10; // Local variable cout << x << endl; } 4 x void fun() x 10 { int x = 10; cout << x << endl; 5 2 } void main() { x = 4; fun(); cout << x << endl; } 55
  • 56. Example of Defining and Using Global and Local Variables #include <iostream.h> int x; // Global variable Void fun(); // function signature x 4 void main() { x = 4; fun(); cout << x << endl; } void fun() { int x = 10; // Local variable cout << x << endl; } 6 void main() { x = 4; fun(); cout << x << endl; } 56
  • 57. Example of Defining and Using Global and Local Variables #include <iostream.h> int x; // Global variable Void fun(); // function signature x 4 void main() { x = 4; fun(); cout << x << endl; } void fun() { int x = 10; // Local variable cout << x << endl; } 7 void main() { x = 4; fun(); cout << x << endl; } 57
  • 58. II. Using Parameters • Function Parameters come in three flavors: – Value parameters – which copy the values of the function arguments – Reference parameters – which refer to the function arguments by other local names and have the ability to change the values of the referenced arguments – Constant reference parameters – similar to the reference parameters but cannot 58 change the values of the referenced
  • 59. Value Parameters • This is what we use to declare in the function signature or function header, e.g. int max (int x, int y); – 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 copies to x and y respectively • Once the value parameters accepted copies of the corresponding arguments data, they act as local variables! 59
  • 60. Example of Using Value Parameters and Global Variables #include <iostream.h> int x; // Global variable void fun(int x) { cout << x << endl; x=x+5; } void main() { x = 4; fun(x/2+1); cout << x << endl; } x 1 0 void main() { x = 4; fun(x/2+1); cout << x << endl; } 60
  • 61. Example of Using Value Parameters and Global Variables #include <iostream.h> int x; // Global variable void fun(int x) { cout << x << endl; x=x+5; } void main() { x = 4; fun(x/2+1); cout << x << endl; } x 3 2 4 void fun(int x ) { cout << x << endl; x=x+5; } void main() { 3 x = 4; fun(x/2+1); cout << x << endl; } 61
  • 62. Example of Using Value Parameters and Global Variables #include <iostream.h> int x; // Global variable void fun(int x) { cout << x << endl; x=x+5; } void main() { x = 4; fun(x/2+1); cout << x << endl; } x 4 2 4 void fun(int x 3 ) 8 { cout << x << endl; x=x+5; } void main() { x = 4; fun(x/2+1); cout << x << endl; } 62
  • 63. Example of Using Value Parameters and Global Variables #include <iostream.h> int x; // Global variable void fun(int x) { cout << x << endl; x=x+5; } void main() { x = 4; fun(x/2+1); cout << x << endl; } x 5 2 4 void fun(int x 3 ) 8 { cout << x << endl; x=x+5; } void main() { x = 4; fun(x/2+1); cout << x << endl; } 63
  • 64. Example of Using Value Parameters and Global Variables #include <iostream.h> int x; // Global variable void fun(int x) { cout << x << endl; x=x+5; } void main() { x = 4; fun(x/2+1); cout << x << endl; } x 6 4 void main() { x = 4; fun(x/2+1); cout << x << endl; } 64
  • 65. Example of Using Value Parameters and Global Variables #include <iostream.h> int x; // Global variable void fun(int x) { cout << x << endl; x=x+5; } void main() { x = 4; fun(x/2+1); cout << x << endl; } x 7 4 void main() { x = 4; fun(x/2+1); cout << x << endl; } 65
  • 66. Reference Parameters • As we saw in the last example, any changes in the value parameters don’t affect the original function arguments • 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); 66
  • 67. Example of Reference Parameters #include <iostream.h> void fun(int &y) { cout << y << endl; y=y+5; } void main() { int x = 4; // Local variable fun(x); cout << x << endl; } 1 void main() { 4 ? int x = 4; fun(x); cout << x << endl; } x 67
  • 68. Example of Reference Parameters #include <iostream.h> void fun(int &y) { cout << y << endl; y=y+5; } void main() { int x = 4; // Local variable fun(x); cout << x << endl; } 3 2 void fun( int & y { cout<<y<<endl; y=y+5; } void main() { 4 ? int x = 4; fun(x); cout << x << endl; } ) x 68
  • 69. Example of Reference Parameters #include <iostream.h> void fun(int &y) { cout << y << endl; y=y+5; } void main() { int x = 4; // Local variable fun(x); cout << x << endl; } 4 2 void fun( int & y { cout<<y<<endl; y=y+5; 9 } void main() { 4 ? int x = 4; fun(x); cout << x << endl; } ) x 69
  • 70. Example of Reference Parameters #include <iostream.h> void fun(int &y) { cout << y << endl; y=y+5; } void main() { int x = 4; // Local variable fun(x); cout << x << endl; } 5 2 void fun( int & y { cout<<y<<endl; y=y+5; } void main() { 9 ? int x = 4; fun(x); cout << x << endl; } ) x 70
  • 71. Example of Reference Parameters #include <iostream.h> void fun(int &y) { cout << y << endl; y=y+5; } void main() { int x = 4; // Local variable fun(x); cout << x << endl; } 6 void main() { 9 ? int x = 4; fun(x); cout << x << endl; } x 71
  • 72. Example of Reference Parameters #include <iostream.h> void fun(int &y) { cout << y << endl; y=y+5; } void main() { int x = 4; // Local variable fun(x); cout << x << endl; } 7 void main() { 9 ? int x = 4; fun(x); cout << x << endl; } x 72
  • 73. Constant Reference Parameters • Constant reference parameters are used under the following two conditions: – The passed data are so big and you want to save time and computer memory – The passed data will not be changed or updated in the function body • For example void report (const string & prompt); • The only valid arguments accepted by reference parameters and constant reference parameters are variable names – It is a syntax error to pass constant values or expressions to the (const) reference parameters 73
  • 74. Header Files • Header files – Contain function prototypes for library functions – <stdlib.h> , <math.h> , etc – Load with #include <filename> #include <math.h> • Custom header files – Create file with functions – Save as filename.h – Load in other files with #include
  • 75. Scope Rules • File scope – Identifier defined outside function, known in all functions – Used for global variables, function definitions, function prototypes • Function scope – Can only be referenced inside a function body – Used only for labels (start:, case: , etc.)
  • 76. Scope Rules • Block scope – Identifier declared inside a block • Block scope begins at declaration, ends at right brace – Used for variables, function parameters (local variables of function) – Outer blocks "hidden" from inner blocks if there is a variable with the same name in the inner block • Function prototype scope