Introduction
Functions allow to structure programs in segments
of code to perform individual tasks.
In C++, a function is ...
Standard Library in a
Programming Language
 The C++ standard consists of two parts: the core language

and the C++ Standa...
 A large part of the C++ library is based on the STL .This provides

useful tools as containers (for example vectors and ...
Function Definition











The general form of a C++ function definition is as follows:
return_type function_nam...
Function Declarations:
 A function declaration tells the compiler about a function





name and how to call the func...
Calling a Function:
 While creating a C++ function, you give a definition

of what the function has to do. To use a funct...
Function Arguments:













If a function is to use arguments, it must declare variables that accept the valu...
Default Values for Parameters:
 When you define a function, you can specify a
default value for each of the last paramete...
About Functions in C++
 Functions invoked by a function–call-statement which consist

of it’s name and information it nee...
Function Calling
• Functions

called by writing

functionName (argument);
or

functionName(argument1, argument2, …);
• Exa...
Function Calling
• Calling/invoking a function
– sqrt(x);
– Parentheses an operator used to call function
• Pass argument ...
Math Library Functions Revisited
Method
ceil( x )

exp( x )

Description
rounds x to the smallest integer
not less than x
...
Function Definition
• Example function
int square( int y )
{
return y * y;
}

• return keyword
– Returns data, and control...
// Creating and using a programmer-defined function.
#include <iostream.h>
int square( int );

// function prototype

Func...
compute square and cube of numbers [1..10] using functions
#include<iostream.h>
int square(int); // prototype
int cube(int...
Function Prototypes


Function prototype contains







Function name
Parameters (number and data type)
Return type...
void Function takes arguments
If the Function does not RETURN result, it is called void
Function
#include<iostream.h>
void...
void Function take no arguments
If the function Does Not Take Arguments specify this with EMPTY-LIST OR
write void inside
...
Remarks on Functions


Local variables





Parameters




Known only in the function in which they are defined
All ...
Remarks on Functions


Omitting the type of returned result defaults to int, but
omitting a non-integer type is a Syntax ...
Local vs Global Variables
#include<iostream.h>
int x,y; //Global Variables
int add2(int, int); //prototype
main()
{ int s;...
Finding Errors in Function Code
int sum(int x, int y)
{
int result;
result = x+y;
}
this function must return an integer ...
Finding Errors in Function Code
void f(float a);
{
float a;
cout<<a<<endl;
}


; found after function definition header.
...
Finding Errors in Function Code
void product(void)
{
int a, b, c, result;
cout << “enter three integers:”;
cin >> a >> b >...
Function Call Methods
Call by value



•

A copy of the value is passed

Call by reference



•

The caller passes the a...
Function Call Methods


Call By Reference



We introduce reference-parameter, to perform call by reference. The caller
...
Function Call Example
#include<iostream.h>
int squareVal(int); //prototype call by value function
void squareRef(int &); /...
Random Number Generator


rand function generates an integer between 0 and RAND-



MAX(~32767) a symbolic constant defi...
Random Number Generator
//generate 10 integers between 5…15
int x;
for ( int i=1; i<=10; i++){
x= rand()%11 + 5;
cout<<x<<...
Random Number Generator




the rand( ) function will generate the same set of
random numbers each time you run the pro...
Randomizing with srand
#include<iostream.h>
#include<iomanip.h>
#include<stdlib.h>
int main()
{
int i;
unsigned num;
// we...
without srand
#include<iostream.h>
#include<iomanip.h>
#include<stdlib.h>

int main()
{
int i;
for(i=1; i<=5; i++)
cout<<s...
Function Overloading


Function overloading
Functions with same name and different parameters
 Should perform similar ta...
C++ Variables
• A variable is a place in memory that has
–
–
–
–

A name or identifier (e.g. income, taxes, etc.)
A data t...
I. Using Global Variables
#include <iostream.h>
int x = 0;
void f1() { x++; }
void f2() { x+=4; f1(); }
void main()
{
f2()...
I. Using Global Variables
#include <iostream.h>
int x = 0;
void f1() { x++; }
void f2() { x+=4; f1(); }
void main()
{
f2()...
I. Using Global Variables
#include <iostream.h>
int x = 0;
void f1() { x++; }
void f2() { x+=4; f1(); }
void main()
{
f2()...
I. Using Global Variables
#include <iostream.h>
int x = 0;
void f1() { x++; }
void f2() { x+=4; f1(); }
void main()
{
f2()...
I. Using Global Variables
#include <iostream.h>
int x = 0;
void f1() { x++; }
void f2() { x+=4; f1(); }
void main()
{
f2()...
I. Using Global Variables
#include <iostream.h>
int x = 0;
void f1() { x++; }
void f2() { x+=4; f1(); }
void main()
{
f2()...
I. Using Global Variables
#include <iostream.h>
int x = 0;
void f1() { x++; }
void f2() { x+=4; f1(); }
void main()
{
f2()...
I. Using Global Variables
#include <iostream.h>
int x = 0;
void f1() { x++; }
void f2() { x+=4; f1(); }
void main()
{
f2()...
I. Using Global Variables
#include <iostream.h>
int x = 0;
void f1() { x++; }
void f2() { x+=4; f1(); }
void main()
{
f2()...
I. Using Global Variables
#include <iostream.h>
int x = 0;
void f1() { x++; }
void f2() { x+=4; f1(); }
void main()
{
f2()...
What is Bad About Using
Global Vairables?
• Not safe!
– If two or more programmers are working together in a
program, one ...
Local Variables
• Local variables are declared inside the function
body and exist as long as the function is running
and d...
Example of Defining and Using Global
and Local Variables
#include <iostream.h>
int x; // Global variable
Void fun(); // fu...
Example of Defining and Using Global
and Local Variables
#include <iostream.h>
int x; // Global variable
Void fun(); // fu...
Example of Defining and Using Global
and Local Variables
#include <iostream.h>
int x; // Global variable
Void fun(); // fu...
Example of Defining and Using Global
and Local Variables
#include <iostream.h>
int x; // Global variable
Void fun(); // fu...
Example of Defining and Using Global
and Local Variables
#include <iostream.h>
int x; // Global variable
Void fun(); // fu...
Example of Defining and Using
Global and Local Variables
#include <iostream.h>
int x; // Global variable
Void fun(); // fu...
Example of Defining and Using
Global and Local Variables
#include <iostream.h>
int x; // Global variable
Void fun(); // fu...
Example of Defining and Using
Global and Local Variables
#include <iostream.h>
int x; // Global variable
Void fun(); // fu...
Example of Defining and Using
Global and Local Variables
#include <iostream.h>
int x; // Global variable
Void fun(); // fu...
II. Using Parameters
• Function Parameters come in three
flavors:
– Value parameters – which copy the
values of the functi...
Value Parameters
• This is what we use to declare in the function signature or
function header, e.g.

int max (int x, int ...
Example of Using Value Parameters
and Global Variables
#include <iostream.h>
int x; // Global variable
void fun(int x)
{
c...
Example of Using Value Parameters
and Global Variables
#include <iostream.h>
int x; // Global variable
void fun(int x)
{
c...
Example of Using Value Parameters
and Global Variables
#include <iostream.h>
int x; // Global variable
void fun(int x)
{
c...
Example of Using Value Parameters
and Global Variables
#include <iostream.h>
int x; // Global variable
void fun(int x)
{
c...
Example of Using Value Parameters
and Global Variables
#include <iostream.h>
int x; // Global variable
void fun(int x)
{
c...
Example of Using Value Parameters
and Global Variables
#include <iostream.h>
int x; // Global variable
void fun(int x)
{
c...
Reference Parameters
• As we saw in the last example, any changes in the
value parameters don’t affect the original functi...
Example of Reference Parameters
#include <iostream.h>
void fun(int &y)
{
cout << y << endl;
y=y+5;
}
void main()
{
int x =...
Example of Reference Parameters
#include <iostream.h>
void fun(int &y)
{
cout << y << endl;
y=y+5;
}
void main()
{
int x =...
Example of Reference Parameters
#include <iostream.h>
void fun(int &y)
{
cout << y << endl;
y=y+5;
}
void main()
{
int x =...
Example of Reference Parameters
#include <iostream.h>
void fun(int &y)
{
cout << y << endl;
y=y+5;
}
void main()
{
int x =...
Example of Reference Parameters
#include <iostream.h>
void fun(int &y)
{
cout << y << endl;
y=y+5;
}
void main()
{
int x =...
Example of Reference Parameters
#include <iostream.h>
void fun(int &y)
{
cout << y << endl;
y=y+5;
}
void main()
{
int x =...
Constant Reference Parameters
• Constant reference parameters are used under
the following two conditions:
– The passed da...
Header Files
• Header files
– Contain function prototypes for library
functions
– <stdlib.h> , <math.h> , etc
– Load with ...
Scope Rules
• File scope
– Identifier defined outside function, known in
all functions
– Used for global variables, functi...
Scope Rules
• Block scope
– Identifier declared inside a block
• Block scope begins at declaration, ends
at right brace
– ...
Thank You
Functions in C++
Functions in C++
Upcoming SlideShare
Loading in...5
×

Functions in C++

1,660

Published on

COmpUTer SciEnce....

Published in: Education
4 Comments
2 Likes
Statistics
Notes
No Downloads
Views
Total Views
1,660
On Slideshare
0
From Embeds
0
Number of Embeds
0
Actions
Shares
0
Downloads
205
Comments
4
Likes
2
Embeds 0
No embeds

No notes for slide

Functions in C++

  1. 1. 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
  2. 2. 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 }
  3. 3. 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).
  4. 4.  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.
  5. 5. 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.
  6. 6. 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.
  7. 7. 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.
  8. 8. 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.
  9. 9. 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.
  10. 10. 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
  11. 11. 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) ) ;
  12. 12. 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)
  13. 13. 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
  14. 14. 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
  15. 15. // 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
  16. 16. 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
  17. 17. 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 ) { … }
  18. 18. 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; }
  19. 19. 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”; }
  20. 20. 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
  21. 21. 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
  22. 22. 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---
  23. 23. 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);
  24. 24. 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; } 
  25. 25. 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;
  26. 26. 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  
  27. 27. 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)
  28. 28. 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 }
  29. 29. 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<<“ “; }
  30. 30. 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<<“ “; }
  31. 31. 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
  32. 32. 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
  33. 33. 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
  34. 34. 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
  35. 35. 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
  36. 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
  37. 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
  38. 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
  39. 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
  40. 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
  41. 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
  42. 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
  43. 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
  44. 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
  45. 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
  46. 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
  47. 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
  48. 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
  49. 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
  50. 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
  51. 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
  52. 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
  53. 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
  54. 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
  55. 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
  56. 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
  57. 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
  58. 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
  59. 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
  60. 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
  61. 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
  62. 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
  63. 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
  64. 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
  65. 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
  66. 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
  67. 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
  68. 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
  69. 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
  70. 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
  71. 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
  72. 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
  73. 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
  74. 74. 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.)
  75. 75. 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
  76. 76. Thank You

×