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:
 ReturnType: 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:
 CallTypeDescription
 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)
 BossToWorker Analogy
 A Boss (the calling/caller function) asks a worker (the called
function) to perform a task and return result when it is done.
Main
Boss
Function A Function B Function Z
Worker
Worker
Function B2Function B1
Worker
Worker Worker Note: usual main( ) Calls other
functions, but other functions can
call each other
Function Calling
 Function Arguments can be:
- Constant sqrt(9);
- Variable sqrt(x);
- Expression sqrt( x*9 + y) ;
sqrt( sqrt(x) ) ;
• 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 Calling
cout<< sqrt(9);
Function Name argument
3
Output
Parentheses used to enclose argument(s)
• 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
Method Description Example
ceil( x ) rounds x to the smallest integer
not less than x
ceil( 9.2 ) is 10.0
ceil( -9.8 ) is -9.0
cos( x ) trigonometric cosine of x
(x in radians)
cos( 0.0 ) is 1.0
exp( x ) exponential function ex exp( 1.0 ) is 2.71828
exp( 2.0 ) is 7.38906
fabs( x ) absolute value of x fabs( 5.1 ) is 5.1
fabs( 0.0 ) is 0.0
fabs( -8.76 ) is 8.76
floor( x ) rounds x to the largest integer
not greater than x
floor( 9.2 ) is 9.0
floor( -9.8 ) is -10.0
fmod( x, y ) remainder of x/y as a floating-
point number
fmod( 13.657, 2.333 ) is 1.992
log( x ) natural logarithm of x (base e) log( 2.718282 ) is 1.0
log( 7.389056 ) is 2.0
log10( x ) logarithm of x (base 10) log10( 10.0 ) is 1.0
log10( 100.0 ) is 2.0
pow( x, y ) x raised to power y (xy) pow( 2, 7 ) is 128
pow( 9, .5 ) is 3
sin( x ) trigonometric sine of x
(x in radians)
sin( 0.0 ) is 0
sqrt( x ) square root of x sqrt( 900.0 ) is 30.0
sqrt( 9.0 ) is 3.0
tan( x ) trigonometric tangent of x
(x in radians)
tan( 0.0 ) is 0
Fig. 3.2 Math library functions.
Math Library Functions Revisited
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
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
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
{
return y * y; // returns square of y as an int
} // end function square
Definition of square. y is a
copy of the argument passed.
Returns y * y, or y squared.
Function prototype: specifies
data types of arguments and
return values. square
expects an int, and returns
an int.
Parentheses () cause function to be called.
When done, it returns the result.
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;
}
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()
{
funA();
funB();
return 0;
}
void funA()
{
cout << “Function-A takes no arqumentsn”;
}
void funB()
{
cout << “Also Function-B takes No argumentsn”;
}
Will be the same
in all cases
void Function take no arguments
 Local variables
 Known only in the function in which they are defined
 All variables declared inside a function are local variables
 Parameters
 Local variables passed to function when called (passing-
parameters)
 Variables defined outside and before function main:
 Called global variables
 Can be accessible and used anywhere in the entire
program
Remarks on Functions
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);
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;
Finding Errors in Function Code
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 called-
function
 Any change to the copy does not affect the original value in the
caller function
 Advantages, prevents side effect, resulting in reliable software
 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 Methods
#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;
}
int squareVal(int a)
{
return a*=a; // caller’s argument not modified
}
void squarRef(int &cRef)
{
cRef *= cRef; // caller’s argument modified
}
x=2 before calling squareVal
4
x=2 after returning
z=4 before calling squareRef
z=16 after returning squareRef
Function Call Example
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<<“ “;
}
//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
Random Number Generator
#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;
}
Randomizing with srand
Output for Multiple Runs
19 6 1 1 4 2 1
18 6 1 5 1 4 4
3 1 2 5 6 2 4
0 1 5 5 3 5 5
3 1 2 5 6 3 4
Different-set of Random
numbers
#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;
}
without srand
Output for Multiple Runs
5 3 3 5 4 2
5 3 3 5 4 2
5 3 3 5 4 2
5 3 3 5 4 2
6 5 3 3 5 4
Same set of numbers for
each run
 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
Function Overloading
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;
}
38
x 0
I. Using Global Variables
#include <iostream.h>
int x = 0;
void f1() { x++; }
void f2() { x+=4; f1(); }
void main()
{
f2();
cout << x << endl;
}
39
x 0
void main()
{
f2();
cout << x << endl ;
}
1
I. Using Global Variables
#include <iostream.h>
int x = 0;
void f1() { x++; }
void f2() { x+=4; f1(); }
void main()
{
f2();
cout << x << endl;
}
40
x 0
void main()
{
f2();
cout << x << endl ;
}
1
void f2()
{
x += 4;
f1();
}
2
4
I. Using Global Variables
#include <iostream.h>
int x = 0;
void f1() { x++; }
void f2() { x+=4; f1(); }
void main()
{
f2();
cout << x << endl;
}
41
45x
void main()
{
f2();
cout << x << endl ;
}
1
void f2()
{
x += 4;
f1();
}
3
void f1()
{
x++;
}
4
I. Using Global Variables
#include <iostream.h>
int x = 0;
void f1() { x++; }
void f2() { x+=4; f1(); }
void main()
{
f2();
cout << x << endl;
}
42
45x
void main()
{
f2();
cout << x << endl;
}
1
void f2()
{
x += 4;
f1();
}
3
void f1()
{
x++;
}5
I. Using Global Variables
#include <iostream.h>
int x = 0;
void f1() { x++; }
void f2() { x+=4; f1(); }
void main()
{
f2();
cout << x << endl;
}
43
45x
void main()
{
f2();
cout << x << endl;
}
1
void f2()
{
x += 4;
f1();
}6
I. Using Global Variables
#include <iostream.h>
int x = 0;
void f1() { x++; }
void f2() { x+=4; f1(); }
void main()
{
f2();
cout << x << endl;
}
44
45x
void main()
{
f2();
cout << x << endl;
}
7
I. Using Global Variables
#include <iostream.h>
int x = 0;
void f1() { x++; }
void f2() { x+=4; f1(); }
void main()
{
f2();
cout << x << endl;
}
45
45x
void main()
{
f2();
cout << x << endl;
}8
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
void main()
{
x = 4;
fun();
cout << x << endl;
}
void fun()
{
int x = 10; // Local variable
cout << x << endl;
}
50
x 0
Global variables are
automatically initialized to 0
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;
}
51
x 0
void main()
{
x = 4;
fun();
cout << x << endl;
}
1
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;
}
52
x 4
void main()
{
x = 4;
fun();
cout << x << endl;
}
2
void fun()
{
int x = 10;
cout << x << endl;
}
x ????
3
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;
}
53
x 4
void main()
{
x = 4;
fun();
cout << x << endl;
}
2
void fun()
{
int x = 10;
cout << x << endl;
}
x 10
3
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;
}
54
x 4
void main()
{
x = 4;
fun();
cout << x << endl;
}
2
void fun()
{
int x = 10;
cout << x << endl;
}
x 10
4
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;
}
55
x 4
void main()
{
x = 4;
fun();
cout << x << endl;
}
2
void fun()
{
int x = 10;
cout << x << endl;
}
x 10
5
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;
}
56
x 4
void main()
{
x = 4;
fun();
cout << x << endl;
}
6
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;
}
57
x 4
void main()
{
x = 4;
fun();
cout << x << endl;
}7
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
change the values of the referenced 58
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;
}
60
x 0
void main()
{
x = 4;
fun(x/2+1);
cout << x << endl;
}
1
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;
}
61
x 4
void main()
{
x = 4;
fun(x/2+1);
cout << x << endl;
}
2
void fun(int x )
{
cout << x << endl;
x=x+5;
}
3
3
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;
}
62
x 4
void main()
{
x = 4;
fun(x/2+1);
cout << x << endl;
}
2
void fun(int x )
{
cout << x << endl;
x=x+5;
}
3
4
8
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;
}
63
x 4
void main()
{
x = 4;
fun(x/2+1);
cout << x << endl;
}
2
void fun(int x )
{
cout << x << endl;
x=x+5;
}
38
5
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;
}
64
x 4
void main()
{
x = 4;
fun(x/2+1);
cout << x << endl;
}
6
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;
}
65
x 4
void main()
{
x = 4;
fun(x/2+1);
cout << x << endl;
}7
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;
}
67
void main()
{
int x = 4;
fun(x);
cout << x << endl;
}
1 x? x4
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;
}
68
void main()
{
int x = 4;
fun(x);
cout << x << endl;
}
2
x? x4
void fun( int & y )
{
cout<<y<<endl;
y=y+5;
}
3
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;
}
69
void main()
{
int x = 4;
fun(x);
cout << x << endl;
}
2
x? x4
void fun( int & y )
{
cout<<y<<endl;
y=y+5;
}
4 9
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;
}
70
void main()
{
int x = 4;
fun(x);
cout << x << endl;
}
2
x? x9
void fun( int & y )
{
cout<<y<<endl;
y=y+5;
}5
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;
}
71
void main()
{
int x = 4;
fun(x);
cout << x << endl;
}
6
x? x9
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;
}
72
void main()
{
int x = 4;
fun(x);
cout << x << endl;
}
x? x9
7
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
Ad

More Related Content

What's hot (20)

FUNCTIONS IN c++ PPT
FUNCTIONS IN c++ PPTFUNCTIONS IN c++ PPT
FUNCTIONS IN c++ PPT
03062679929
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
home
 
Lecture#6 functions in c++
Lecture#6 functions in c++Lecture#6 functions in c++
Lecture#6 functions in c++
NUST Stuff
 
Inline function
Inline functionInline function
Inline function
Tech_MX
 
Call by value
Call by valueCall by value
Call by value
Dharani G
 
Function
FunctionFunction
Function
jayesh30sikchi
 
Functions in c++
Functions in c++Functions in c++
Functions in c++
Abdullah Turkistani
 
Parameter passing to_functions_in_c
Parameter passing to_functions_in_cParameter passing to_functions_in_c
Parameter passing to_functions_in_c
ForwardBlog Enewzletter
 
Functions in c++
Functions in c++Functions in c++
Functions in c++
Maaz Hasan
 
Function overloading(C++)
Function overloading(C++)Function overloading(C++)
Function overloading(C++)
Ritika Sharma
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
Sachin Sharma
 
Lecture#7 Call by value and reference in c++
Lecture#7 Call by value and reference in c++Lecture#7 Call by value and reference in c++
Lecture#7 Call by value and reference in c++
NUST Stuff
 
C++ programming function
C++ programming functionC++ programming function
C++ programming function
Vishalini Mugunen
 
Call by value or call by reference in C++
Call by value or call by reference in C++Call by value or call by reference in C++
Call by value or call by reference in C++
Sachin Yadav
 
Inline Functions and Default arguments
Inline Functions and Default argumentsInline Functions and Default arguments
Inline Functions and Default arguments
Nikhil Pandit
 
Function in c
Function in cFunction in c
Function in c
CGC Technical campus,Mohali
 
C++ Function
C++ FunctionC++ Function
C++ Function
PingLun Liao
 
RECURSION IN C
RECURSION IN C RECURSION IN C
RECURSION IN C
v_jk
 
C++ functions
C++ functionsC++ functions
C++ functions
Dawood Jutt
 
Function in c program
Function in c programFunction in c program
Function in c program
umesh patil
 
FUNCTIONS IN c++ PPT
FUNCTIONS IN c++ PPTFUNCTIONS IN c++ PPT
FUNCTIONS IN c++ PPT
03062679929
 
Functions in C++
Functions in C++Functions in C++
Functions in C++
home
 
Lecture#6 functions in c++
Lecture#6 functions in c++Lecture#6 functions in c++
Lecture#6 functions in c++
NUST Stuff
 
Inline function
Inline functionInline function
Inline function
Tech_MX
 
Call by value
Call by valueCall by value
Call by value
Dharani G
 
Functions in c++
Functions in c++Functions in c++
Functions in c++
Maaz Hasan
 
Function overloading(C++)
Function overloading(C++)Function overloading(C++)
Function overloading(C++)
Ritika Sharma
 
Lecture#7 Call by value and reference in c++
Lecture#7 Call by value and reference in c++Lecture#7 Call by value and reference in c++
Lecture#7 Call by value and reference in c++
NUST Stuff
 
Call by value or call by reference in C++
Call by value or call by reference in C++Call by value or call by reference in C++
Call by value or call by reference in C++
Sachin Yadav
 
Inline Functions and Default arguments
Inline Functions and Default argumentsInline Functions and Default arguments
Inline Functions and Default arguments
Nikhil Pandit
 
RECURSION IN C
RECURSION IN C RECURSION IN C
RECURSION IN C
v_jk
 
Function in c program
Function in c programFunction in c program
Function in c program
umesh patil
 

Viewers also liked (14)

Functions
FunctionsFunctions
Functions
Online
 
Basics of c++ Programming Language
Basics of c++ Programming LanguageBasics of c++ Programming Language
Basics of c++ Programming Language
Ahmad Idrees
 
Standard Library Functions
Standard Library FunctionsStandard Library Functions
Standard Library Functions
Praveen M Jigajinni
 
C++ functions presentation by DHEERAJ KATARIA
C++ functions presentation by DHEERAJ KATARIAC++ functions presentation by DHEERAJ KATARIA
C++ functions presentation by DHEERAJ KATARIA
Dheeraj Kataria
 
Modular programming
Modular programmingModular programming
Modular programming
Mohanlal Sukhadia University (MLSU)
 
4 introduction to programming structure
4 introduction to programming structure4 introduction to programming structure
4 introduction to programming structure
Rheigh Henley Calderon
 
Netw450 advanced network security with lab entire class
Netw450 advanced network security with lab entire classNetw450 advanced network security with lab entire class
Netw450 advanced network security with lab entire class
EugenioBrown1
 
C++ L05-Functions
C++ L05-FunctionsC++ L05-Functions
C++ L05-Functions
Mohammad Shaker
 
Top down design
Top down designTop down design
Top down design
Chaffey College
 
C++ functions
C++ functionsC++ functions
C++ functions
Dawood Jutt
 
5 structured programming
5 structured programming 5 structured programming
5 structured programming
hccit
 
Functions c++ مشروع
Functions c++ مشروعFunctions c++ مشروع
Functions c++ مشروع
ziadalmulla
 
Network-security muhibullah aman-first edition-in Persian
Network-security muhibullah aman-first edition-in PersianNetwork-security muhibullah aman-first edition-in Persian
Network-security muhibullah aman-first edition-in Persian
Muhibullah Aman
 
Network Security in 2016
Network Security in 2016Network Security in 2016
Network Security in 2016
Qrator Labs
 
Functions
FunctionsFunctions
Functions
Online
 
Basics of c++ Programming Language
Basics of c++ Programming LanguageBasics of c++ Programming Language
Basics of c++ Programming Language
Ahmad Idrees
 
C++ functions presentation by DHEERAJ KATARIA
C++ functions presentation by DHEERAJ KATARIAC++ functions presentation by DHEERAJ KATARIA
C++ functions presentation by DHEERAJ KATARIA
Dheeraj Kataria
 
4 introduction to programming structure
4 introduction to programming structure4 introduction to programming structure
4 introduction to programming structure
Rheigh Henley Calderon
 
Netw450 advanced network security with lab entire class
Netw450 advanced network security with lab entire classNetw450 advanced network security with lab entire class
Netw450 advanced network security with lab entire class
EugenioBrown1
 
5 structured programming
5 structured programming 5 structured programming
5 structured programming
hccit
 
Functions c++ مشروع
Functions c++ مشروعFunctions c++ مشروع
Functions c++ مشروع
ziadalmulla
 
Network-security muhibullah aman-first edition-in Persian
Network-security muhibullah aman-first edition-in PersianNetwork-security muhibullah aman-first edition-in Persian
Network-security muhibullah aman-first edition-in Persian
Muhibullah Aman
 
Network Security in 2016
Network Security in 2016Network Security in 2016
Network Security in 2016
Qrator Labs
 
Ad

Similar to Functions in C++ (20)

Ch4 functions
Ch4 functionsCh4 functions
Ch4 functions
Hattori Sidek
 
Python Functions.pptx
Python Functions.pptxPython Functions.pptx
Python Functions.pptx
AnuragBharti27
 
Python Functions.pptx
Python Functions.pptxPython Functions.pptx
Python Functions.pptx
AnuragBharti27
 
User defined function in C.pptx
User defined function in C.pptxUser defined function in C.pptx
User defined function in C.pptx
Rhishav Poudyal
 
Functions
FunctionsFunctions
Functions
zeeshan841
 
Cpp functions
Cpp functionsCpp functions
Cpp functions
NabeelaNousheen
 
1.6 Function.pdf
1.6 Function.pdf1.6 Function.pdf
1.6 Function.pdf
NirmalaShinde3
 
All chapters C++ - Copy.pdfyttttttttttttttttttttttttttttt
All chapters C++ - Copy.pdfytttttttttttttttttttttttttttttAll chapters C++ - Copy.pdfyttttttttttttttttttttttttttttt
All chapters C++ - Copy.pdfyttttttttttttttttttttttttttttt
jacobdiriba
 
Py-Slides-3 difficultpythoncoursefforbeginners.ppt
Py-Slides-3 difficultpythoncoursefforbeginners.pptPy-Slides-3 difficultpythoncoursefforbeginners.ppt
Py-Slides-3 difficultpythoncoursefforbeginners.ppt
mohamedsamydeveloper
 
C language presentation
C language presentationC language presentation
C language presentation
bainspreet
 
Powerpoint presentation for Python Functions
Powerpoint presentation for Python FunctionsPowerpoint presentation for Python Functions
Powerpoint presentation for Python Functions
BalaSubramanian376976
 
Amit user defined functions xi (2)
Amit  user defined functions xi (2)Amit  user defined functions xi (2)
Amit user defined functions xi (2)
Arpit Meena
 
programlama fonksiyonlar c++ hjhjghjv jg
programlama fonksiyonlar c++ hjhjghjv jgprogramlama fonksiyonlar c++ hjhjghjv jg
programlama fonksiyonlar c++ hjhjghjv jg
uleAmet
 
Unit_5Functionspptx__2022_12_27_10_47_17 (1).pptx
Unit_5Functionspptx__2022_12_27_10_47_17 (1).pptxUnit_5Functionspptx__2022_12_27_10_47_17 (1).pptx
Unit_5Functionspptx__2022_12_27_10_47_17 (1).pptx
vekariyakashyap
 
Function in c
Function in cFunction in c
Function in c
Raj Tandukar
 
CH.4FUNCTIONS IN C_FYBSC(CS).pptx
CH.4FUNCTIONS IN C_FYBSC(CS).pptxCH.4FUNCTIONS IN C_FYBSC(CS).pptx
CH.4FUNCTIONS IN C_FYBSC(CS).pptx
SangeetaBorde3
 
functions _
functions                                 _functions                                 _
functions _
SwatiHans10
 
functions modules and exceptions handlings.ppt
functions modules and exceptions handlings.pptfunctions modules and exceptions handlings.ppt
functions modules and exceptions handlings.ppt
Rajasekhar364622
 
Ch06
Ch06Ch06
Ch06
Arriz San Juan
 
Storage Classes and Functions
Storage Classes and FunctionsStorage Classes and Functions
Storage Classes and Functions
Jake Bond
 
User defined function in C.pptx
User defined function in C.pptxUser defined function in C.pptx
User defined function in C.pptx
Rhishav Poudyal
 
All chapters C++ - Copy.pdfyttttttttttttttttttttttttttttt
All chapters C++ - Copy.pdfytttttttttttttttttttttttttttttAll chapters C++ - Copy.pdfyttttttttttttttttttttttttttttt
All chapters C++ - Copy.pdfyttttttttttttttttttttttttttttt
jacobdiriba
 
Py-Slides-3 difficultpythoncoursefforbeginners.ppt
Py-Slides-3 difficultpythoncoursefforbeginners.pptPy-Slides-3 difficultpythoncoursefforbeginners.ppt
Py-Slides-3 difficultpythoncoursefforbeginners.ppt
mohamedsamydeveloper
 
C language presentation
C language presentationC language presentation
C language presentation
bainspreet
 
Powerpoint presentation for Python Functions
Powerpoint presentation for Python FunctionsPowerpoint presentation for Python Functions
Powerpoint presentation for Python Functions
BalaSubramanian376976
 
Amit user defined functions xi (2)
Amit  user defined functions xi (2)Amit  user defined functions xi (2)
Amit user defined functions xi (2)
Arpit Meena
 
programlama fonksiyonlar c++ hjhjghjv jg
programlama fonksiyonlar c++ hjhjghjv jgprogramlama fonksiyonlar c++ hjhjghjv jg
programlama fonksiyonlar c++ hjhjghjv jg
uleAmet
 
Unit_5Functionspptx__2022_12_27_10_47_17 (1).pptx
Unit_5Functionspptx__2022_12_27_10_47_17 (1).pptxUnit_5Functionspptx__2022_12_27_10_47_17 (1).pptx
Unit_5Functionspptx__2022_12_27_10_47_17 (1).pptx
vekariyakashyap
 
CH.4FUNCTIONS IN C_FYBSC(CS).pptx
CH.4FUNCTIONS IN C_FYBSC(CS).pptxCH.4FUNCTIONS IN C_FYBSC(CS).pptx
CH.4FUNCTIONS IN C_FYBSC(CS).pptx
SangeetaBorde3
 
functions modules and exceptions handlings.ppt
functions modules and exceptions handlings.pptfunctions modules and exceptions handlings.ppt
functions modules and exceptions handlings.ppt
Rajasekhar364622
 
Storage Classes and Functions
Storage Classes and FunctionsStorage Classes and Functions
Storage Classes and Functions
Jake Bond
 
Ad

Recently uploaded (20)

The ever evoilving world of science /7th class science curiosity /samyans aca...
The ever evoilving world of science /7th class science curiosity /samyans aca...The ever evoilving world of science /7th class science curiosity /samyans aca...
The ever evoilving world of science /7th class science curiosity /samyans aca...
Sandeep Swamy
 
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Library Association of Ireland
 
How to manage Multiple Warehouses for multiple floors in odoo point of sale
How to manage Multiple Warehouses for multiple floors in odoo point of saleHow to manage Multiple Warehouses for multiple floors in odoo point of sale
How to manage Multiple Warehouses for multiple floors in odoo point of sale
Celine George
 
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Library Association of Ireland
 
Unit 4: Long term- Capital budgeting and its types
Unit 4: Long term- Capital budgeting and its typesUnit 4: Long term- Capital budgeting and its types
Unit 4: Long term- Capital budgeting and its types
bharath321164
 
Marie Boran Special Collections Librarian Hardiman Library, University of Gal...
Marie Boran Special Collections Librarian Hardiman Library, University of Gal...Marie Boran Special Collections Librarian Hardiman Library, University of Gal...
Marie Boran Special Collections Librarian Hardiman Library, University of Gal...
Library Association of Ireland
 
To study Digestive system of insect.pptx
To study Digestive system of insect.pptxTo study Digestive system of insect.pptx
To study Digestive system of insect.pptx
Arshad Shaikh
 
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Library Association of Ireland
 
Vitamins Chapter-7, Biochemistry and clinical pathology, D.Pharm 2nd year
Vitamins Chapter-7, Biochemistry and clinical pathology, D.Pharm 2nd yearVitamins Chapter-7, Biochemistry and clinical pathology, D.Pharm 2nd year
Vitamins Chapter-7, Biochemistry and clinical pathology, D.Pharm 2nd year
ARUN KUMAR
 
Unit 5: Dividend Decisions and its theories
Unit 5: Dividend Decisions and its theoriesUnit 5: Dividend Decisions and its theories
Unit 5: Dividend Decisions and its theories
bharath321164
 
Fundamentals of PR: Wk 4 - Strategic Communications
Fundamentals of PR: Wk 4 - Strategic CommunicationsFundamentals of PR: Wk 4 - Strategic Communications
Fundamentals of PR: Wk 4 - Strategic Communications
Jordan Williams
 
Quality Contril Analysis of Containers.pdf
Quality Contril Analysis of Containers.pdfQuality Contril Analysis of Containers.pdf
Quality Contril Analysis of Containers.pdf
Dr. Bindiya Chauhan
 
Timber Pitch Roof Construction Measurement-2024.pptx
Timber Pitch Roof Construction Measurement-2024.pptxTimber Pitch Roof Construction Measurement-2024.pptx
Timber Pitch Roof Construction Measurement-2024.pptx
Tantish QS, UTM
 
Studying Drama: Definition, types and elements
Studying Drama: Definition, types and elementsStudying Drama: Definition, types and elements
Studying Drama: Definition, types and elements
AbdelFattahAdel2
 
LDMMIA Reiki Master Spring 2025 Mini Updates
LDMMIA Reiki Master Spring 2025 Mini UpdatesLDMMIA Reiki Master Spring 2025 Mini Updates
LDMMIA Reiki Master Spring 2025 Mini Updates
LDM Mia eStudios
 
YSPH VMOC Special Report - Measles Outbreak Southwest US 4-30-2025.pptx
YSPH VMOC Special Report - Measles Outbreak  Southwest US 4-30-2025.pptxYSPH VMOC Special Report - Measles Outbreak  Southwest US 4-30-2025.pptx
YSPH VMOC Special Report - Measles Outbreak Southwest US 4-30-2025.pptx
Yale School of Public Health - The Virtual Medical Operations Center (VMOC)
 
YSPH VMOC Special Report - Measles Outbreak Southwest US 4-26-2025.pptx
YSPH VMOC Special Report - Measles Outbreak  Southwest US 4-26-2025.pptxYSPH VMOC Special Report - Measles Outbreak  Southwest US 4-26-2025.pptx
YSPH VMOC Special Report - Measles Outbreak Southwest US 4-26-2025.pptx
Yale School of Public Health - The Virtual Medical Operations Center (VMOC)
 
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACYUNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
DR.PRISCILLA MARY J
 
Operations Management (Dr. Abdulfatah Salem).pdf
Operations Management (Dr. Abdulfatah Salem).pdfOperations Management (Dr. Abdulfatah Salem).pdf
Operations Management (Dr. Abdulfatah Salem).pdf
Arab Academy for Science, Technology and Maritime Transport
 
Diabetic neuropathy peripheral autonomic
Diabetic neuropathy peripheral autonomicDiabetic neuropathy peripheral autonomic
Diabetic neuropathy peripheral autonomic
Pankaj Patawari
 
The ever evoilving world of science /7th class science curiosity /samyans aca...
The ever evoilving world of science /7th class science curiosity /samyans aca...The ever evoilving world of science /7th class science curiosity /samyans aca...
The ever evoilving world of science /7th class science curiosity /samyans aca...
Sandeep Swamy
 
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Niamh Lucey, Mary Dunne. Health Sciences Libraries Group (LAI). Lighting the ...
Library Association of Ireland
 
How to manage Multiple Warehouses for multiple floors in odoo point of sale
How to manage Multiple Warehouses for multiple floors in odoo point of saleHow to manage Multiple Warehouses for multiple floors in odoo point of sale
How to manage Multiple Warehouses for multiple floors in odoo point of sale
Celine George
 
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Phoenix – A Collaborative Renewal of Children’s and Young People’s Services C...
Library Association of Ireland
 
Unit 4: Long term- Capital budgeting and its types
Unit 4: Long term- Capital budgeting and its typesUnit 4: Long term- Capital budgeting and its types
Unit 4: Long term- Capital budgeting and its types
bharath321164
 
Marie Boran Special Collections Librarian Hardiman Library, University of Gal...
Marie Boran Special Collections Librarian Hardiman Library, University of Gal...Marie Boran Special Collections Librarian Hardiman Library, University of Gal...
Marie Boran Special Collections Librarian Hardiman Library, University of Gal...
Library Association of Ireland
 
To study Digestive system of insect.pptx
To study Digestive system of insect.pptxTo study Digestive system of insect.pptx
To study Digestive system of insect.pptx
Arshad Shaikh
 
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Michelle Rumley & Mairéad Mooney, Boole Library, University College Cork. Tra...
Library Association of Ireland
 
Vitamins Chapter-7, Biochemistry and clinical pathology, D.Pharm 2nd year
Vitamins Chapter-7, Biochemistry and clinical pathology, D.Pharm 2nd yearVitamins Chapter-7, Biochemistry and clinical pathology, D.Pharm 2nd year
Vitamins Chapter-7, Biochemistry and clinical pathology, D.Pharm 2nd year
ARUN KUMAR
 
Unit 5: Dividend Decisions and its theories
Unit 5: Dividend Decisions and its theoriesUnit 5: Dividend Decisions and its theories
Unit 5: Dividend Decisions and its theories
bharath321164
 
Fundamentals of PR: Wk 4 - Strategic Communications
Fundamentals of PR: Wk 4 - Strategic CommunicationsFundamentals of PR: Wk 4 - Strategic Communications
Fundamentals of PR: Wk 4 - Strategic Communications
Jordan Williams
 
Quality Contril Analysis of Containers.pdf
Quality Contril Analysis of Containers.pdfQuality Contril Analysis of Containers.pdf
Quality Contril Analysis of Containers.pdf
Dr. Bindiya Chauhan
 
Timber Pitch Roof Construction Measurement-2024.pptx
Timber Pitch Roof Construction Measurement-2024.pptxTimber Pitch Roof Construction Measurement-2024.pptx
Timber Pitch Roof Construction Measurement-2024.pptx
Tantish QS, UTM
 
Studying Drama: Definition, types and elements
Studying Drama: Definition, types and elementsStudying Drama: Definition, types and elements
Studying Drama: Definition, types and elements
AbdelFattahAdel2
 
LDMMIA Reiki Master Spring 2025 Mini Updates
LDMMIA Reiki Master Spring 2025 Mini UpdatesLDMMIA Reiki Master Spring 2025 Mini Updates
LDMMIA Reiki Master Spring 2025 Mini Updates
LDM Mia eStudios
 
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACYUNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
UNIT 3 NATIONAL HEALTH PROGRAMMEE. SOCIAL AND PREVENTIVE PHARMACY
DR.PRISCILLA MARY J
 
Diabetic neuropathy peripheral autonomic
Diabetic neuropathy peripheral autonomicDiabetic neuropathy peripheral autonomic
Diabetic neuropathy peripheral autonomic
Pankaj Patawari
 

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:  ReturnType: 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:  CallTypeDescription  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)  BossToWorker Analogy  A Boss (the calling/caller function) asks a worker (the called function) to perform a task and return result when it is done. Main Boss Function A Function B Function Z Worker Worker Function B2Function B1 Worker Worker Worker Note: usual main( ) Calls other functions, but other functions can call each other
  • 12. Function Calling  Function Arguments can be: - Constant sqrt(9); - Variable sqrt(x); - Expression sqrt( x*9 + y) ; sqrt( sqrt(x) ) ; • 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
  • 13. Function Calling cout<< sqrt(9); Function Name argument 3 Output Parentheses used to enclose argument(s) • 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
  • 14. Method Description Example ceil( x ) rounds x to the smallest integer not less than x ceil( 9.2 ) is 10.0 ceil( -9.8 ) is -9.0 cos( x ) trigonometric cosine of x (x in radians) cos( 0.0 ) is 1.0 exp( x ) exponential function ex exp( 1.0 ) is 2.71828 exp( 2.0 ) is 7.38906 fabs( x ) absolute value of x fabs( 5.1 ) is 5.1 fabs( 0.0 ) is 0.0 fabs( -8.76 ) is 8.76 floor( x ) rounds x to the largest integer not greater than x floor( 9.2 ) is 9.0 floor( -9.8 ) is -10.0 fmod( x, y ) remainder of x/y as a floating- point number fmod( 13.657, 2.333 ) is 1.992 log( x ) natural logarithm of x (base e) log( 2.718282 ) is 1.0 log( 7.389056 ) is 2.0 log10( x ) logarithm of x (base 10) log10( 10.0 ) is 1.0 log10( 100.0 ) is 2.0 pow( x, y ) x raised to power y (xy) pow( 2, 7 ) is 128 pow( 9, .5 ) is 3 sin( x ) trigonometric sine of x (x in radians) sin( 0.0 ) is 0 sqrt( x ) square root of x sqrt( 900.0 ) is 30.0 sqrt( 9.0 ) is 3.0 tan( x ) trigonometric tangent of x (x in radians) tan( 0.0 ) is 0 Fig. 3.2 Math library functions. Math Library Functions Revisited
  • 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 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 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 { return y * y; // returns square of y as an int } // end function square Definition of square. y is a copy of the argument passed. Returns y * y, or y squared. Function prototype: specifies data types of arguments and return values. square expects an int, and returns an int. Parentheses () cause function to be called. When done, it returns the result. 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. 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() { funA(); funB(); return 0; } void funA() { cout << “Function-A takes no arqumentsn”; } void funB() { cout << “Also Function-B takes No argumentsn”; } Will be the same in all cases void Function take no arguments
  • 21.  Local variables  Known only in the function in which they are defined  All variables declared inside a function are local variables  Parameters  Local variables passed to function when called (passing- parameters)  Variables defined outside and before function main:  Called global variables  Can be accessible and used anywhere in the entire program Remarks on Functions
  • 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. 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
  • 26. 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; Finding Errors in Function Code
  • 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 called- function  Any change to the copy does not affect the original value in the caller function  Advantages, prevents side effect, resulting in reliable software
  • 28.  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 Methods
  • 29. #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; } int squareVal(int a) { return a*=a; // caller’s argument not modified } void squarRef(int &cRef) { cRef *= cRef; // caller’s argument modified } x=2 before calling squareVal 4 x=2 after returning z=4 before calling squareRef z=16 after returning squareRef Function Call Example
  • 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. //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
  • 32.  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 Random Number Generator
  • 33. #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; } Randomizing with srand Output for Multiple Runs 19 6 1 1 4 2 1 18 6 1 5 1 4 4 3 1 2 5 6 2 4 0 1 5 5 3 5 5 3 1 2 5 6 3 4 Different-set of Random numbers
  • 34. #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; } without srand Output for Multiple Runs 5 3 3 5 4 2 5 3 3 5 4 2 5 3 3 5 4 2 5 3 3 5 4 2 6 5 3 3 5 4 Same set of numbers for each run
  • 35.  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 Function Overloading
  • 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; } 38 x 0
  • 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; } 39 x 0 void main() { f2(); cout << x << endl ; } 1
  • 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; } 40 x 0 void main() { f2(); cout << x << endl ; } 1 void f2() { x += 4; f1(); } 2 4
  • 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; } 41 45x void main() { f2(); cout << x << endl ; } 1 void f2() { x += 4; f1(); } 3 void f1() { x++; } 4
  • 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; } 42 45x void main() { f2(); cout << x << endl; } 1 void f2() { x += 4; f1(); } 3 void f1() { x++; }5
  • 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; } 43 45x void main() { f2(); cout << x << endl; } 1 void f2() { x += 4; f1(); }6
  • 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; } 44 45x void main() { f2(); cout << x << endl; } 7
  • 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; } 45 45x void main() { f2(); cout << x << endl; }8
  • 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 void main() { x = 4; fun(); cout << x << endl; } void fun() { int x = 10; // Local variable cout << x << endl; } 50 x 0 Global variables are automatically initialized to 0
  • 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; } 51 x 0 void main() { x = 4; fun(); cout << x << endl; } 1
  • 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; } 52 x 4 void main() { x = 4; fun(); cout << x << endl; } 2 void fun() { int x = 10; cout << x << endl; } x ???? 3
  • 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; } 53 x 4 void main() { x = 4; fun(); cout << x << endl; } 2 void fun() { int x = 10; cout << x << endl; } x 10 3
  • 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; } 54 x 4 void main() { x = 4; fun(); cout << x << endl; } 2 void fun() { int x = 10; cout << x << endl; } x 10 4
  • 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; } 55 x 4 void main() { x = 4; fun(); cout << x << endl; } 2 void fun() { int x = 10; cout << x << endl; } x 10 5
  • 56. 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; } 56 x 4 void main() { x = 4; fun(); cout << x << endl; } 6
  • 57. 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; } 57 x 4 void main() { x = 4; fun(); cout << x << endl; }7
  • 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 change the values of the referenced 58
  • 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; } 60 x 0 void main() { x = 4; fun(x/2+1); cout << x << endl; } 1
  • 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; } 61 x 4 void main() { x = 4; fun(x/2+1); cout << x << endl; } 2 void fun(int x ) { cout << x << endl; x=x+5; } 3 3
  • 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; } 62 x 4 void main() { x = 4; fun(x/2+1); cout << x << endl; } 2 void fun(int x ) { cout << x << endl; x=x+5; } 3 4 8
  • 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; } 63 x 4 void main() { x = 4; fun(x/2+1); cout << x << endl; } 2 void fun(int x ) { cout << x << endl; x=x+5; } 38 5
  • 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; } 64 x 4 void main() { x = 4; fun(x/2+1); cout << x << endl; } 6
  • 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; } 65 x 4 void main() { x = 4; fun(x/2+1); cout << x << endl; }7
  • 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; } 67 void main() { int x = 4; fun(x); cout << x << endl; } 1 x? x4
  • 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; } 68 void main() { int x = 4; fun(x); cout << x << endl; } 2 x? x4 void fun( int & y ) { cout<<y<<endl; y=y+5; } 3
  • 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; } 69 void main() { int x = 4; fun(x); cout << x << endl; } 2 x? x4 void fun( int & y ) { cout<<y<<endl; y=y+5; } 4 9
  • 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; } 70 void main() { int x = 4; fun(x); cout << x << endl; } 2 x? x9 void fun( int & y ) { cout<<y<<endl; y=y+5; }5
  • 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; } 71 void main() { int x = 4; fun(x); cout << x << endl; } 6 x? x9
  • 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; } 72 void main() { int x = 4; fun(x); cout << x << endl; } x? x9 7
  • 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