Buildin Functions The contents of this lecture prepared

Build-in Functions The contents of this lecture prepared by the instructors at the University of Manitoba in Canada and modified by Dr. Ahmad Reza Hadaegh A. R. Hadaegh Dr. Ahmad R. Hadaegh National University Page 1

Functions - A method for allowing a program to be implemented in pieces - A function is a block of code that performs some operations and (possibly) gives back a result - Suppose you were doing something really basic - e. g. opening a file, calculating a square root - Silly to write code for this over and over - Much easier to include it in a library of routines and reuse it whenever you want A. R. Hadaegh Dr. Ahmad R. Hadaegh National University Page 2

Functions - This is what happens whenever you use a #include to make use of a library of routines (a header file) - e. g. when you include fstream, you get access to a routine to open a file - also other routines we haven’t used yet - Someone has written a set of functions, that you can make use of when you include the appropriate header file A. R. Hadaegh Dr. Ahmad R. Hadaegh National University Page 3

Built-In functions - There are many of these built-in functions and correspondingly, many header files - For example, say you want to calculate a square root. That’s in the math header file. #include<cmath> A. R. Hadaegh Dr. Ahmad R. Hadaegh National University Page 4

Built- In Functions #include <cmath> #include <iostream> using namespace std; int main () { float num, answer; cout << “Enter a value: ”; cin >> num; answer = sqrt(num); cout << “The square root of ” << num << “ is ” << answer << endl; } < See Example 1> A. R. Hadaegh Dr. Ahmad R. Hadaegh National University Page 5

Built- In Functions - sqrt is the name of the function - num is the value we want to take the square root of - Like this one, functions require specific information to perform their jobs - Parameters A. R. Hadaegh Dr. Ahmad R. Hadaegh National University Page 6

Supplying Arguments answer = sqrt( 3. 7); answer = sqrt(6+2); -When we call a function, we supply specific values (arguments) for the parameters the function requires - They are supplied in brackets when we call the function - more on these terms later - Arguments can be specified directly (i. e. as literals), in variables or constants, or as the result of complex expressions A. R. Hadaegh Dr. Ahmad R. Hadaegh National University Page 7

Supplying Arguments answer = pow(3, 7); - If we have to supply several arguments, we separate them by commas - pow (also in math header file) calculates its first argument raised to the power of its second (37). - The order of the arguments is important – if we reversed them, we’d get 73 ! A. R. Hadaegh Dr. Ahmad R. Hadaegh National University Page 8

Calling Built- In Functions - What happens when we call a built-in function? - The arguments we supply are evaluated, and passed to the function - The function runs (code we don’t see - from the header file) - The function eventually completes - Often it calculates and returns a result A. R. Hadaegh Dr. Ahmad R. Hadaegh National University Page 9

Returning a Result - When a function returns a result, it will have a specific type – e. g: both pow and sqrt return floats - We have to do something with this result – Store it: answer = sqrt(X); – Print it: cout << sqrt(X); – Pass it on to other calculations: x = 2 + pow(7, 14); y = sqrt( pow(2, 4)); A. R. Hadaegh Dr. Ahmad R. Hadaegh National University Page 10

Output Formatting Functions - In the iomanip header file - Allow us to create more nicely formatted output #include <iostream> #include <iomanip> using namespace std; int main () { int x = 4; cout << setw(5) << x << endl; } - setw sets the width (# spaces) the next data item should take up! < see: Example 2> A. R. Hadaegh Dr. Ahmad R. Hadaegh National University Page 11

Output Formatting Functions cout << setw( 5) << x; - Pads with blanks on left to appropriate length. Here, bbbb 4 would be printed (where b = blank) - Only works for the next item (i. e. you have to repeat this if you want the same formatting) - Default for setw is 0 - leaves just enough room for value - What about real numbers (floats)? A. R. Hadaegh Dr. Ahmad R. Hadaegh National University Page 12

Formatting Floats - The way in which floats are formatted depends on your compiler - The text gives a few lines that sets up floating point formatting for whatever you’re using cout. setf(ios: : fixed, ios: : floatfield); cout. setf( ios: : showpoint); - once you’ve done this (just copy in the lines, don’t even worry what they do) you can set the decimal point precision A. R. Hadaegh Dr. Ahmad R. Hadaegh National University Page 13

Formatting Floats • setprecision( ) sets the number of decimal places to print #include <iostream> #include <iomanip> using namespace std; int main () { cout. setf(ios: : fixed, ios: : floatfield); cout. setf( ios: : showpoint); cout << setprecision(3); float x = 4. 7589; cout << setw(7) << x; } • Output: bb 4. 759 (where b= blank) < See: Example 3> A. R. Hadaegh Dr. Ahmad R. Hadaegh National University Page 14

Output Formatting Function - Note the rounding - the number is rounded off for printing - doesn’t change the value in the variable at all - The width will be increased if necessary to fit the number - Unlike setw, setprecision has lasting effects - once used, all floats will continue to be printed that way until you change it A. R. Hadaegh Dr. Ahmad R. Hadaegh National University Page 15

User- Defined Functions - So, we know how to use functions provided for us by other programmers - There are lots of them, but they obviously don’t cover everything we want - We want to be able to write our own functions! A. R. Hadaegh Dr. Ahmad R. Hadaegh National University Page 16

User Defined Functions - Why? ? - So we can re-use them later if we want - So we can divide our programs into pieces - Re-use has obvious advantages – more compact programs, no repeated code, and not having to rewrite code later for similar problems - But why would we want to divide a program into pieces? A. R. Hadaegh Dr. Ahmad R. Hadaegh National University Page 17

Dividing Programs into Pieces - To make the program more manageable - If we have pieces of a program that do individual tasks, we can isolate errors and modifications - Take the square root routine for example… if you had to write it… - You could test it separately from the rest of your program; errors found later are not as likely to be in the square root function! - You could modify the internals of the function without affecting the rest of your program! A. R. Hadaegh Dr. Ahmad R. Hadaegh National University Page 18

Dividing Programs into Pieces - Before we talk about how to create our own functions, we need to talk about dividing programs up - Obviously, we don’t just do it randomly A. R. Hadaegh Dr. Ahmad R. Hadaegh National University Page 19

Top-Down Design - A technique for designing programs - Useful without even knowing anything about functions - Helps us to handle the “where do I start? ” - Lets us gradually design a program without being overwhelmed by details A. R. Hadaegh Dr. Ahmad R. Hadaegh National University Page 20

Top-Down Design - Begin with a high-level statement of the problem - Clearly this is not something that you could implement directly - but it does give you a general statement of what you’re trying to do - Now break this into smaller problems A. R. Hadaegh Dr. Ahmad R. Hadaegh National University Page 21

Top-Down Design Update prices for big sale Ask user for % off Change prices - Asking the user is pretty much implementable at this point (a concrete step) - Change prices is still pretty vague (abstract step), so we can break that one down too. . . A. R. Hadaegh Dr. Ahmad R. Hadaegh National University Page 22

Top-Down Design Change prices Open price files Read a price Discount price Print new price - Now everything is concrete - we’re done! - Each box is a module, The entire diagram is a structure chart and shows how modules are related - Each module should be functionally cohesive - it should do one, well-defined thing A. R. Hadaegh Dr. Ahmad R. Hadaegh National University Page 23

Top-Down Design - You should always do a design for each program - Gives you a handle on where to start - Ensures you know what you’re doing before you start programming! - You should only start implementing after your design is complete! A. R. Hadaegh Dr. Ahmad R. Hadaegh National University Page 24

User-Defined Functions The contents of this lecture prepared by the instructors at the University of Manitoba in Canada and modified by Dr. Ahmad Reza Hadaegh A. R. Hadaegh Dr. Ahmad R. Hadaegh National University Page 25

User- Defined Functions - Functions are a facility provided by C++ to implement the modules in your design - Allows each module to be physically separate from others and re-used as necessary - We’ve already been using user-defined functions. Every C++ program starts with one function called main(); we add others as necessary A. R. Hadaegh Dr. Ahmad R. Hadaegh National University Page 26

User- Defined Functions - Are similar to built-in functions - They have a name, parameters, can return a result, and are called exactly like built in functions - So we know a lot about them already! - Let’s look at a simple example A. R. Hadaegh Dr. Ahmad R. Hadaegh National University Page 27

Simple Function Example Function Header Information about the function void printabar() { cout << “***************”; } Function Body statements that perform the function’s task - The function header contains information like the name, what data it needs to do its job, etc. More on this in a moment A. R. Hadaegh Dr. Ahmad R. Hadaegh National University Page 28

Simple Function Example void printabar() { cout << “***************”; } - Notice how similar this is to the programs we’ve been writing so far? - That’s because main() is a function! - All C++ programs have a function called main, and that is where execution of the program begins A. R. Hadaegh Dr. Ahmad R. Hadaegh National University Page 29

Simple Function Example void printabar() { cout << “***************”; } - How do we make use of this function? - We call it, just like a built-in function - use it’s name and brackets: printabar(); A. R. Hadaegh Dr. Ahmad R. Hadaegh National University Page 30

Simple Function Example void printabar() { cout << “***************”; } - We know what one looks like, we know how to call it, but where do we put them? - We already have one function in our program - main() - We can put them in any order, but main() usually comes first - so we can get an immediate overview of what the program does before looking at the details - There’s a problem with this though…. . A. R. Hadaegh Dr. Ahmad R. Hadaegh National University Page 31

Declaration Before Use - Many languages, including both C++ and Pascal, have a rule that forces you to declare anything you want to use before you use it - That’s why we have to declare variables! - This is a problem in functions. Suppose I want to call my printabar function inside main. If main comes first, how will the compiler know what I’m talking about!? ! A. R. Hadaegh Dr. Ahmad R. Hadaegh National University Page 32

Declaration Before Use void main () { printabar(); } //-------------void printabar() { We try to use printabar here But because its down here, the compiler hasn’t even seen it yet we will get an error every time we use it } We could put printabar (and other functions we want to use) first; then, however, we’d have to hunt through all these details before we got down to main and found out what the program actually does! A. R. Hadaegh Dr. Ahmad R. Hadaegh National University Page 33

Prototypes - There is a solution to this problem - a special statement that lets the compiler know what upcoming functions are going to look like before actually implementing them - A Prototype - Since most of the information about a function is in its header, it will look pretty much like the function header itself - There will be a few differences we will see later when we look at more complicated functions - Lets look at the whole thing using a prototype A. R. Hadaegh Dr. Ahmad R. Hadaegh National University Page 34

Prototypes Example #include <iostream> using namespace std; void printabar (); This prototype tells C++ everything it needs to figure out if you are calling printabar properly or not void main () { // this is the main program pretend there’s // lots of other statements here printabar(); } // end main //----------------------void printabar() { // printbar code goes here } // end printbar A. R. Hadaegh Dr. Ahmad R. Hadaegh National University Page 35

Prototypes Example #include <iostream> using namespace std; void printabar (); void main () { // this is the main program // pretend there’s lots of other statements here printabar(); } // end main void printabar() { All the functions we use can now immediately follow main, provided each has a prototype that appears before main // printabar code goes here // pretend there’s some statements here } // end printabar A. R. Hadaegh Dr. Ahmad R. Hadaegh National University Page 36

More Complex Functions - We now know a fair bit about functions: - What one looks like - Where they appear in the program - how to call them - But our functions don’t do much yet. Lets look at some more complex situations A. R. Hadaegh Dr. Ahmad R. Hadaegh National University Page 37

Parameters - Our printabar function is so trivial, it doesn’t really do much of anything - Like most built-in functions, our own functions will generally require some information to work with - Say we wanted to use printabar to print bars for a line graph -bars aren’t always the same length - When we wanted to use the function, we’d have to provide some data indicating the number of characters to print A. R. Hadaegh Dr. Ahmad R. Hadaegh National University Page 38

Parameters - We indicate in our function that data will be provided when we call the function by declaring parameters - A parameter acts like a variable (details later), and holds the value we give to the function when we call it - You will also see Parameters called Formal Parameters - because they’re defined formally as part of the function A. R. Hadaegh Dr. Ahmad R. Hadaegh National University Page 39

Using Parameters void printabar (int numchars) { int count= 1; while (count <= numchars) { // loop to print 1 char at a time cout << ‘*’; count++; //incrementing the counter } cout << endl; } - Here’s our function with a parameter added - We define its type and give it a name - We can have a list of parameters separated by commas (like declaring a bunch of variables) A. R. Hadaegh Dr. Ahmad R. Hadaegh National University Page 40

Using Parameters void printabar (int numchars) { int count= 1; while (count <= numchars) { // loop to print 1 char @ a time cout << ‘* ’; count++; // remember to increment counter! } cout << endl; } - Note that we don’t give the parameter a value!!! The value will be supplied when we call the function A. R. Hadaegh Dr. Ahmad R. Hadaegh National University Page 41

Arguments void main () { printabar(6); printabar(3); } - Now we need to specify a value between the brackets when we call printabar - This is an argument - data we supply to work with at the time we call the function - Arguments are also called Actual Parameters - Arguments are matched to parameters by ORDER (we’ll talk about it later) A. R. Hadaegh Dr. Ahmad R. Hadaegh National University Page 42

Parameters and Prototypes void printabar(int); - Here you see the appropriate prototype for the function with parameters - Note its now a little different from the function header - Prototypes give C++ the info it needs to tell if you are correctly calling the function - It needs the name, needs to know if there are parameters and what type they are, but doesn’t care about their names - The names are optional; you only really need to list the types of the parameters in order <See: Example 4> A. R. Hadaegh Dr. Ahmad R. Hadaegh National University Page 43

Call by Value Call by Reference The contents of this lecture prepared by the instructors at the University of Manitoba in Canada and modified by Dr. Ahmad Reza Hadaegh A. R. Hadaegh Dr. Ahmad R. Hadaegh National University Page 44

Returning Values - The examples we’ve seen so far are very different from most built-in functions we’ve used - They just do something - they don’t give any answer back! - Most built- in functions calculate something and return it (sqrt, pow, etc. ) - How can we do this? A. R. Hadaegh Dr. Ahmad R. Hadaegh National University Page 45

Void and Non-Void Functions - Every function has a type - Part of the header, tells C++ what type of value the function will give back when we call it - The first word of the header defines the type of the function - The functions we’ve used so far don’t return values - The type void is used to indicate this - If you want to return a value, simply supply the type you want instead of void A. R. Hadaegh Dr. Ahmad R. Hadaegh National University Page 46

Non- Void Functions Note >1 parameter int mypower (int x, int y) { // raise x to power y (y >= 0) using a count- controlled loop int count= 1; // loop counter int answer= 1; // holds the answer while (count <= y) Causes function to { // loop to print 1 char @ a time terminate and send back value we’ve answer = answer * x; specified count++; } // end while return answer; } // send answer back to caller A. R. Hadaegh Dr. Ahmad R. Hadaegh National University Page 47

Calling Non-Void Functions - When we call this function, just like most built-in functions, we need to do something with the result: - Store it: answer = mypower(x, y); - Print it: cout << mypower(2, 3); - Pass it on to other calculations: x = 2 + mypower(7, 14); y= sqrt( mypower(2, 4)); - Remember that the order of arguments matters!!! A. R. Hadaegh Dr. Ahmad R. Hadaegh National University Page 48

Prototypes for Non-Void Functions - For a prototype of this function, we need to add the type information (just as we needed to use void in earlier examples) int mypower( int x, int y); - Remember that you can actually put the parameter names if you want, but they’re irrelevant A. R. Hadaegh Dr. Ahmad R. Hadaegh National University Page 49

More on Return - Return may also be useful in terminating a function prematurely - You can use it anywhere in the function, and you can use it without a value in a void function to simply cause the function to terminate early - Example: while (1) { cin >> x; if (x < 0) return; else // lots of other code } A. R. Hadaegh Dr. Ahmad R. Hadaegh National University Page 50

More on Return - Is also commonly used in the main function - we usually give the main function a type of int, and return some integer indicating whether the program ran correctly - e. g. return 0 for no error, higher numbers for more severe problems int main () { // whatever main does return 0; } - The text uses this; feel free to use it if you want A. R. Hadaegh Dr. Ahmad R. Hadaegh National University Page 51

So far… - We have functions which implement the modules in our program designs - These functions can accept arguments, which provide data for the function to work with - These functions can also return results if we want them to A. R. Hadaegh Dr. Ahmad R. Hadaegh National University Page 52

Returning more than one result - But suppose we want to return more than one result? - Suppose you wanted an interactive program that would calculate volume for the user. - You repeatedly want to obtain length, width, and height - This might be something you want a separate function for - But how? A function can only return one result. . . but there are ways around this A. R. Hadaegh Dr. Ahmad R. Hadaegh National University Page 53

Parameter Types - The answer lies in a new type of parameter we haven’t seen yet - Recall that the parameters we have used so far act like variables: - They get created when a function is called - A value is passed into them from the caller - They cease to exist when the function returns - So given that, what do you think would happen in the following example: A. R. Hadaegh Dr. Ahmad R. Hadaegh National University Page 54

Example int strange( int); int main() { int arg = 7; cout << strange(arg); cout << endl << arg ; } int strange( int y) { y = 6; return 0; } < See Example 5 > A. R. Hadaegh Dr. Ahmad R. Hadaegh We print the result of calling strange, which is 0 (the value returned by strange) But what’s happening here? We print arg, which is 7 Or is it? When we call strange, we change it’s parameter to 6…. National University Page 55

Altering Parameter Values - According to what we know happens with parameters, 7 should be printed - That’s because - the parameter y is created when the function runs - the argument is copied into it (the 7). . . - and even though we change y to 6, y itself is destroyed when the function returns - So our original argument, arg (with the value 7) is never touched and can’t be! A. R. Hadaegh Dr. Ahmad R. Hadaegh National University Page 56

Parameter Types - But it doesn’t always have to be this way! - We are making use of only one of two types of parameters allowed by C++ - These are called Value Parameters, because as the name implies, the argument values are copied into the parameter, and the original argument can never be changed - There’s a second type that DOES allow argument values to be changed A. R. Hadaegh Dr. Ahmad R. Hadaegh National University Page 57

Reference Parameters - This second type is called a Reference Parameter - For the moment, just assume that when you declare one, you’re allowed to actually make changes to the argument being passed - We can and do use this to return values from functions - Since we can have as many parameters as we want, we can return as many values as we’d like in them by altering the parameters! A. R. Hadaegh Dr. Ahmad R. Hadaegh National University Page 58

Reference Parameters - Very easy to declare - just put an ampersand (&) at the end of the data type of the parameter name: int& x - So, when writing functions, just ask yourself if you want the original argument to be changeable, and if you do, add the ampersand! - Let’s see our strange example with reference parameters. . . A. R. Hadaegh Dr. Ahmad R. Hadaegh National University Page 59

Example int strange( int&); int main() { int arg = 7; cout << strange(arg); cout << endl << arg ; } The parameter y is now a Reference Parameter - this means that whatever we pass to y can be altered! int strange( int& y) { y = 6; return 0; } < See: Example 6 > A. R. Hadaegh Dr. Ahmad R. Hadaegh National University Page 60

Example int strange( int&); int main() { int arg = 7; cout << strange(arg); cout << endl << arg ; } int strange(int& y) { y = 6; return 0; } A. R. Hadaegh Dr. Ahmad R. Hadaegh So arg is passed to strange y will be 7 as before y will be set to the value 6. . . National University Page 61

Example int strange( int&); int main() { int arg = 7; cout << strange( arg); cout << endl << arg ; } arg, after the call to strange, will also have the value 6! int strange( int& y) { y = 6; int answer = y*2; return answer; } - Obviously, we have to be careful with these! A. R. Hadaegh Dr. Ahmad R. Hadaegh National University Page 62

Mechanics of Reference Parameters - It’s important to understand what’s going on here - First of all, reference parameters don’t behave any differently than value parameters - They’re still created when the function is called - They still get an argument from outside - They’re still destroyed when the function returns A. R. Hadaegh Dr. Ahmad R. Hadaegh National University Page 63

Mechanics of Reference Parameters - Then how can they work the way they do? - Do they copy the parameter back into the argument when the function returns? - No, they don’t do that either - Their behavior has everything to do with WHAT is actually being passed A. R. Hadaegh Dr. Ahmad R. Hadaegh National University Page 64

Mechanics of Reference Parameters - In a value parameter, the actual value of the argument is copied into the parameter arg 7 …. …. y 7 - The 7 is copied over and then strange runs A. R. Hadaegh Dr. Ahmad R. Hadaegh National University Page 65

Mechanics of Reference Parameters - In a reference parameter, the value is not passed; the memory address of the argument is! arg y 7 …. …. - In fact, ‘y’ becomes an alias name for variable ‘arg’. Any change in ‘y’ makes the same change in ‘arg’ A. R. Hadaegh Dr. Ahmad R. Hadaegh National University Page 66

Back to our Example - More importantly , considering the full example: int strange( int& ); int main() { int arg = 7; cout << strange( arg); cout << endl << arg ; } So when strange returns, arg has the value 6, and that is what is printed! int strange( int& y) { y = 6; return 0; } A. R. Hadaegh Dr. Ahmad R. Hadaegh National University Page 67

Something to Remember - You never have to worry about the address business yourself! - You don’t care in this example what the address of arg happens to be; the compiler handles all this for you - This is an example of what’s properly called a pointer, something we’ll study in advanced C++ course A. R. Hadaegh Dr. Ahmad R. Hadaegh National University Page 68

Returning Multiple Values - We can use reference parameters to return as many values as we want - In our original example, we wanted to read in length, width and height - It’s easy now! A. R. Hadaegh Dr. Ahmad R. Hadaegh National University Page 69

Returning Multiple Values int main() { float l, w, h; getvalues(l, w, h); cout << “volume is “ << l*w*h; } //------------------------void getvalues(float& len, float& wid, float& height) { cout << “enter an integer length: ”; cin >> len; cout << “enter an integer width: ”; cin >> wid; cout << “enter an integer height: ”; cin >> height; } < See: Example 7> A. R. Hadaegh Dr. Ahmad R. Hadaegh National University Page 70

Returning Multiple Values - getvalues doesn’t return anything. . . - instead, it has three reference parameters - when we input values, we change these, and change the variables the caller supplies! - Getvalues takes l, w, h as arguments, and because each of its parameters is a reference parameter, it actually modifies l, w, and h, effectively allowing the function to give back three values A. R. Hadaegh Dr. Ahmad R. Hadaegh National University Page 71

Returning Multiple Values - But suppose I did this! int main() { int l, w, h; getvalues( 6, 2, 3); // other code after this } - It doesn’t make sense does it? How can the function change a 6, or a 2? ? ? It can only change what’s stored in a variable! A. R. Hadaegh Dr. Ahmad R. Hadaegh National University Page 72

Big Restriction - We can only pass variables to reference parameters! - As in the last example, this should make sense, because they’re the only things that can be modified - i. e. the only things that have an address that can be referred to - There’s one other thing to be aware of A. R. Hadaegh Dr. Ahmad R. Hadaegh National University Page 73

Watch out for Type Coercion! - We’ve seen that C++ tries to convert types to allow the statements we make - e. g. converting characters to integers using the collating sequence if we assign a character to an integer - Odd things happen if we do this in a reference parameter - since the types don’t match, it can’t use them directly - instead, it creates a second variable, coerces, and uses that - Unexpected result can happen - so make the types to be the same when using call by reference A. R. Hadaegh Dr. Ahmad R. Hadaegh National University Page 74

Use Reference Parameters Carefully! - It’s easy to make changes to arguments you don’t intend - Such changes can be hard to trace back! - Don’t use reference parameters unless you want values passed back - There always exceptions, but treat this as a rule for now! A. R. Hadaegh Dr. Ahmad R. Hadaegh National University Page 75

Scope and Lifetime of Global and Local Variables The contents of this lecture prepared by the instructors at the University of Manitoba in Canada and modified by Dr. Ahmad Reza Hadaegh A. R. Hadaegh Dr. Ahmad R. Hadaegh National University Page 76

Scope and Lifetime - The scope of a variable is the region in which it is accessible in a program - we have seen many examples of scope already void main() { int x; . . } void foo() { x= 5; } - illegal: the scope of x is only the function main x is undefined in foo A. R. Hadaegh Dr. Ahmad R. Hadaegh National University Page 77

Scope and Lifetime: Global - Variables generally global or local in scope - Global variables: – declared outside any function in program file ofstream fout; void main() { fout. open("outfile. txt"); . . . ; } void foo() { fout << "Print this to outfile. txt"; } - fout is declared globally - it is accessible to any function in the program file A. R. Hadaegh Dr. Ahmad R. Hadaegh National University Page 78

Scope and Lifetime: Global - Usually only make input/output streams and constants global const float Pi= 3. 14159; const int Array. Size= 1000; ifstream fin; ofstream fout; void main() {. . . } void foo() {. . . } - all constants and globals are accessible in main and foo A. R. Hadaegh Dr. Ahmad R. Hadaegh National University Page 79

Scope and Lifetime: Global - const globals should be used whenever a literal is used which most probably not going to be changed - this makes your program much more - readable: the reader is not always attempting to figure out what a literal is for - changeable: need only change the literal once at top (instead of throughout program) A. R. Hadaegh Dr. Ahmad R. Hadaegh National University Page 80

Scope and Lifetime: Global - The lifetime of a variable is the portion of program execution during which the variable has memory allocated to it - the time during which the variable exists - the time during which values stored to a variable remain stored A. R. Hadaegh Dr. Ahmad R. Hadaegh National University Page 81

Scope and Lifetime: Local - Local variables are those declared as - local variables in a function (including main) - formal parameters in a function - any local variables in any block: {. . . } - A block of code is the code between {. . . } - the body of any function is a block void printabar() { cout << "********" << endl; Code } Block A. R. Hadaegh Dr. Ahmad R. Hadaegh National University Page 82

Scope and Lifetime: Local - Any block can have local variables void strange( int x ) { Block of function strange: int y; Block includes x, y y= x; if (y== 3) { Block between {. . . } int z; Block includes z z= y; cout << x << “ ”<< y <<“ ” << z; } } < See: Example 8> A. R. Hadaegh Dr. Ahmad R. Hadaegh National University Page 83

Scope and Lifetime: Local - All local variables are enclosed in some block of code - The scope of a local variable is from the point of declaration to the end of the block - remember, variables don't need to be declared at the top of a block (but probably should be. . . ) void foo( int x) { cout << x; int y; x= y; cout << y; Scope of y } A. R. Hadaegh Dr. Ahmad R. Hadaegh National University Page 84

Scope and Lifetime: Local - The lifetime of a local variable or parameter: - Begins when execution of code enters the block containing the declaration - Ends when execution leaves the block of code containing the declaration - Local variables and parameters are called automatic variables - memory is automatically allocated when the block is entered - memory is automatically reclaimed when the block is exited A. R. Hadaegh Dr. Ahmad R. Hadaegh National University Page 85

Scope and Lifetime: Local - Consider the following situation float exp( float x) { int y; if (x>- 0. 5 && x< 0. 5) { for (y= 0; y< 10; y++) {. . . . } } } Block A Block B - y not declared in the block B of function exp – but y is certainly accessible within block B A. R. Hadaegh Dr. Ahmad R. Hadaegh National University Page 86

Scope and Lifetime: Local - The variable y is non-local to Block B - y is defined as local in a block containing block B - Generally, a non-local variable for a block of code is either - a global variable (which are non- local to all blocks of code) - a local variable defined in a block containing the block under consideration - Global, non- local, and local variables are generally accessible in any block contained in the block in which they are defined A. R. Hadaegh Dr. Ahmad R. Hadaegh National University Page 87

Scope and Lifetime const float pi= 3. 14159; // an approximation int main() { const float pi= 22. 0 / 7. 0; // in elementary school { const int pi = 3; // in the state of Indiana cout << pi; } } - only "const int pi = 3" is visible at the cout statement A. R. Hadaegh Dr. Ahmad R. Hadaegh National University Page 88

Scope and Lifetime - In this case, the innermost definition of the variable pi is the one used by cout - this is called name precedence - when a variable name is used in a statement, it refers to the definition of that variable in the smallest or innermost block containing the statement A. R. Hadaegh Dr. Ahmad R. Hadaegh National University Page 89

Scope and Lifetime void func 1 (int, char&); void func 2( ); int a 1; char a 2; int main() {. . . . } void func 1 (int a 1, char& b 2) { int c 1; int d 2; // variables used are : a 1 a 2 c 1 d 2 b 2 } What is the scope of each variable used in func 1? A. R. Hadaegh Dr. Ahmad R. Hadaegh National University Page 90

Scope and Lifetime void func 2(); int a 1; char a 2; // repeat definitions for convenience void func 2() { int a 1; int b 2; while (. . . ) { int c 1; int b 2; } } - What is the scope of each variable used in func 2? A. R. Hadaegh Dr. Ahmad R. Hadaegh National University Page 91
- Slides: 91