Pass by Value More Functions Different location in memory Changes to the parameters inside the function body have no effect outside of the function. 2 Passing Parameters by Reference Example: Exchange two numbers If we use pass by value, it will not work!!! To have a function with multiple outputs, we have to use pass by reference. Reference (address) of parameter is passed to the function, instead of its value. If the function changes the parameter value, the changes will be reflected in the program calling it. How to pass parameters by reference: <type>& <variable>,..., <type>& <variable> a and num1 are in the same location in memory Also b and num2 3 Pass by value and by reference 5 Storage Classes Storage class specifiers Storage class Where object exists in memory Scope Where object is referenced in program Linkage Where an identifier is known Automatic storage Object created and destroyed within its block auto Default for local variables. Example: auto float x, y; register Tries to put variables into high-speed registers Can only be used with local variables and parameters 6 1
Storage Class Each variable has a storage class. Determines the period during which the variable exists in memory. Some variables are created only once (memory is set aside to hold the variable value) Global variables are created only once. Some variables are re-created many times Local variables are re-created each time a function is called. Block Scope int main(void) int y; int a = y; cout << a << endl; cout << a << endl; Error a doesn t exist outside the block! 7 8 Storage Classes Static storage Variables exist for entire program execution static Local variables defined in functions Keep value after function ends Only known in their own function Extern Default for global variables and functions. Known in any function Specifying Storage Class auto int j; register int i_need_to_be_fast; static char remember_me; extern double a_global; 9 10 Lifetime of Local Automatic Variables Their storage is created (allocated) when control enters the function Local variables are alive while function is executing Their storage is destroyed (deallocated) when function exits Lifetime of Global Variables Their lifetime is the lifetime of the entire program Their memory is allocated when program begins execution Their memory is deallocated when the entire program terminates 11 12 2
Automatic vs. Static Variable Storage for automatic variable is allocated at block entry and deallocated at block exit Storage for static variable remains allocated throughout execution of the entire program Default Allocation Local variables are automatic To obtain a static local variable, you must use the reserved word static in its declaration 13 1 Static and Automatic Local Variables int popularsquare(int n) static int timescalled = 0; // Initialized only once int result = n * n; // Initialized each time timescalled = timescalled + 1; cout << Call # << timescalled << endl; return result; static example int countcalls(void) static int count = 0; count++; return(count); cout << countcalls() << endl; cout << countcalls() << endl; cout << countcalls() << endl; 15 15 16 Scope of Identifier The scope of an identifier (or named constant) is the region of program code in which it is legal to use that identifier for any purpose Local Scope The scope of an identifier that is declared inside a block (this includes function parameters) extends from the point of declaration to the end of the block vs. Global Scope The scope of an identifier that is declared outside of all namespaces, functions, and classes extends from point of declaration to the end of the entire file containing the program code 17 18 3
const float TAX_RATE = 0.05; // Global constant float tiprate; // Global variable void handle (int, float); // Function prototype using namespace std; int main () int age; // age and bill local to this block float bill;. // a, b, and tax are local to main. // TAX_RATE and tiprate can be used handle (age, bill); return 0; void handle (int a, float b) float tax; // a, b, and tax local to this block. // age and bill if used must be declared as local to handle. // TAX_RATE and tiprate can be used Scope Rules 1 Function names have global scope 2 A function parameter s scope is identical to the scope of a local variable declared in the outermost block of the function body 3 A global variable s (or constant s) scope extends from its declaration to the end of the file. A local variable s (or constant s) scope extends from its declaration to the end of the block in which it is declared, including any nested blocks. 19 19 20 1 // Example 1 2 // A scoping example 3 #include <iostream> 5 using std::cout; 6 using std::endl; 7 8 void a( void ); // function prototype 9 void b( void ); // function prototype 10 void c( void ); // function prototype 11 x is different inside and outside 12 int x = 1; // global variable the block. 13 1 int main() 15 16 int x = 5; // local variable to main 17 18 cout << "local x in outer scope of main is " << x << endl; 19 20 21 // int x = 7; start new scope 1. Function prototypes 22 23 cout << "local in inner scope of main is " << x << endl; x 2 // end new scope 25 26 cout << "local x in outer scope of main is " << x << endl; 27 28 a(); // a has automatic local x 29 b(); // b has static local x local x in outer scope of main is 5 30 c(); // c uses global x local x in inner scope of main is 7 31 a(); // a reinitializes automatic local x in local outer x scope of main is 5 32 b(); // static local x retains its previous value 33 c(); // global 1.2 x also Initialize retains its value local variable 3 1.1 Initialize global variable 35 cout << "local x in main is " << x << endl; 36 37 return 0; Local automatic variables are 38 39 created and destroyed each 0 void a( void ) time a is called. 1 2 int x = 25; // initialized each time a is called 3 cout << endl << "local x in a is " << x 5 << " after entering a" << endl; local x in a is 25 after entering a 6 ++x; local x in a is 26 before exiting a 7 cout << "local x in a is " << x 8 << " before exiting a" << endl; 9 50 51 void b( void ) 52 Local static variables are 53 static int x = 50; // Static initialization only not destroyed when the 5 // first time b is called. 55 cout << endl << "local static x is " << x function ends. 3.1 Define Functions 56 << " on entering b" << endl; 57 ++x; local static x is 50 on entering b 58 cout << "local static x is " << x local static x is 51 on exiting b 59 << " on exiting b" << endl; 60 61 Global variables are always 62 void c( void ) accessible. Function c 63 references the global x. 6 cout << endl << "global x is " << x global x is 1 on entering c 65 << " on entering c" << endl; 66 x *= 10; global x is 10 on exiting c 67 cout << "global x is " << x << " on exiting c" << endl; 68 Unary Scope Resolution Operator local x in outer scope of main is 5 local x in inner scope of main is 7 local x in outer scope of main is 5 local x in a is 25 after entering a local x in a is 26 before exiting a local static x is 50 on entering b local static x is 51 on exiting b global x is 1 on entering c global x is 10 on exiting c local x in a is 25 after entering a local x in a is 26 before exiting a local static x is 51 on entering b local static x is 52 on exiting b global x is 10 on entering c global x is 100 on exiting c local x in main is 5 Program Output Unary scope resolution operator (::) Access global variables if a local variable has same name not needed if names are different instead of variable use ::variable 2
1 // Example 2 2 // Using the unary scope resolution operator 3 #include <iostream> 5 using std::cout; 6 using std::endl; 7 8 #include <iomanip> 9 10 using std::setprecision; 11 12 const double PI = 3.1159265358979; 13 1 int main() 15 16 const float PI = static_cast< float >( ::PI ); 17 18 cout << setprecision( 20 ) 19 << " Local float value of PI = " << PI 20 << "\nglobal double value of PI = " << ::PI << endl; 21 22 return 0; 23 Local float value of PI = 3.115927101257322 Global double value of PI = 3.11592653589790007 Notice the use of :: Practical Use of Storage Class Local variables are auto by default. Global variables are static by default. Declaring a local variable as static means it will remember it s last value (it s not destroyed and recreated each time it s scope is entered). 26 Revisiting Motivation We already saw several mechanisms that can support having similar functions for handling various types: Macros: #define SWAP(a,b) Using function overloading we can implement several functions with the same name that differ only in the parameter s type. For example : swap() void swap(int& a, int& b) int temp = a; void swap(float& a, float& b) float temp = a; void swap(char*& a, char*& b) char* temp = a; Introduction It would be very beneficial if we could implement only one function which will describe the swap() function (which is similar to all types) and still work for every type. Using we can do just that Example: void swap(t& a, T& b) T temp = a; void main() int i=, j=9; swap(i, j); char* str1 = hello ; char* str2 = world ; Swap(str1, str2); The line informs the compiler that this is a template functions, including a general type T, and that it should unfold the function according to the various options, T will receive. copyrights Elhanan Borenstein How Does it work? A template function actually represents a collections of functions. For each (different) usage (activation of the function with a different type) of the function: the compiler will first create the appropriate copy of the function and then compile that copy Will that code work? void dosomething( int I ) T a, b; b = a = i; Guidelines The template function must be included (directly or through #include) in the file that makes use of it (WHY?) a.cpp b.cpp void Swap(T& a, T& b) a.cpp void Swap(T& a, T& b) a.h void Swap(T& a, T& b) void main() Swap(i, j); b.cpp void Swap(T& a, T& b) void main() Swap(i, j); b.cpp #include a.h void main() Swap(i, j); 5
Format More than one general type can be defined. For example: template<class key, class value> Using the name T, is optional Instead of <class T> we can also use <typename T> For each class T, only one type can be used when calling the function no casting 6