Your SlideShare is downloading. ×
Scope, binding, papameter passing techniques
Scope, binding, papameter passing techniques
Scope, binding, papameter passing techniques
Scope, binding, papameter passing techniques
Scope, binding, papameter passing techniques
Scope, binding, papameter passing techniques
Scope, binding, papameter passing techniques
Scope, binding, papameter passing techniques
Scope, binding, papameter passing techniques
Scope, binding, papameter passing techniques
Scope, binding, papameter passing techniques
Scope, binding, papameter passing techniques
Scope, binding, papameter passing techniques
Scope, binding, papameter passing techniques
Scope, binding, papameter passing techniques
Scope, binding, papameter passing techniques
Scope, binding, papameter passing techniques
Scope, binding, papameter passing techniques
Scope, binding, papameter passing techniques
Scope, binding, papameter passing techniques
Scope, binding, papameter passing techniques
Scope, binding, papameter passing techniques
Scope, binding, papameter passing techniques
Scope, binding, papameter passing techniques
Scope, binding, papameter passing techniques
Scope, binding, papameter passing techniques
Scope, binding, papameter passing techniques
Scope, binding, papameter passing techniques
Scope, binding, papameter passing techniques
Scope, binding, papameter passing techniques
Scope, binding, papameter passing techniques
Scope, binding, papameter passing techniques
Scope, binding, papameter passing techniques
Scope, binding, papameter passing techniques
Scope, binding, papameter passing techniques
Scope, binding, papameter passing techniques
Upcoming SlideShare
Loading in...5
×

Thanks for flagging this SlideShare!

Oops! An error has occurred.

×
Saving this for later? Get the SlideShare app to save on your phone or tablet. Read anywhere, anytime – even offline.
Text the download link to your phone
Standard text messaging rates apply

Scope, binding, papameter passing techniques

2,529

Published on

Chapter 1 Introduction 9 …

Chapter 1 Introduction 9
Variables 9
Data types 9
System defined data types (Primitive data types) 10
User defined data types 10
Data Structure 10
Abstract Data Types (ADT’s) 11
Memory and Variables 11
Size of a Variable 12
Address of a Variable 12
Pointers 13
Declaration of Pointers 13
Pointers Usage 13
Pointer Manipulation 14
Arrays and Pointers 15
Dynamic Memory Allocation 15
Function Pointers 16
Parameter Passing Techniques 16
Actual and Formal Parameters 16
Semantics of Parameter Passing 17
Language Support for Parameter Passing Techniques 17
Pass by Value 17
Pass by Result 18
Pass by Value-Result 19
Pass by Reference (aliasing) 20
Pass by Name 21
Binding 22
Binding Times 22
Static Binding (Early binding) 22
Dynamic Binding (Late binding) 23
Scope 23
Static Scope 23
Dynamic Scope 24
Storage Classes 25
Auto Storage Class 25
Extern storage class 26
Register Storage Class 31
Static Storage Class 31
Storage Organization 32
Static Segment 32
Stack Segment 33
Heap Segment 35
Shallow Copy versus Deep Copy 36

Published in: Business, Technology
1 Comment
0 Likes
Statistics
Notes
  • Be the first to like this

No Downloads
Views
Total Views
2,529
On Slideshare
0
From Embeds
0
Number of Embeds
1
Actions
Shares
0
Downloads
133
Comments
1
Likes
0
Embeds 0
No embeds

Report content
Flagged as inappropriate Flag as inappropriate
Flag as inappropriate

Select your reason for flagging this presentation as inappropriate.

Cancel
No notes for slide

Transcript

  • 1. To My Parents -Laxmi and ModaiahTo My Wife -SailajaTo My Family MembersTo My FriendsTo IIT BombayTo All Hard Workers
  • 2. Copyright ©2010 by CareerMonk.com All rights reserved.Designed by Narasimha Karumanchi Printed in India
  • 3. Table of ContentsChapter 1 Introduction ............................................................................................................... 9 Variables ................................................................................................................................................... 9 Data types ................................................................................................................................................. 9 System defined data types (Primitive data types) ............................................................................ 10 User defined data types...................................................................................................................... 10 Data Structure ........................................................................................................................................ 10 Abstract Data Types (ADT’s) ................................................................................................................. 11 Memory and Variables .......................................................................................................................... 11 Size of a Variable................................................................................................................................ 12 Address of a Variable ......................................................................................................................... 12 Pointers................................................................................................................................................... 13 Declaration of Pointers ...................................................................................................................... 13 Pointers Usage .................................................................................................................................... 13 Pointer Manipulation ........................................................................................................................ 14 Arrays and Pointers ........................................................................................................................... 15 Dynamic Memory Allocation............................................................................................................ 15 Function Pointers............................................................................................................................... 16 Parameter Passing Techniques .............................................................................................................. 16 Actual and Formal Parameters .......................................................................................................... 16 Semantics of Parameter Passing ........................................................................................................ 17 Language Support for Parameter Passing Techniques ..................................................................... 17 Pass by Value...................................................................................................................................... 17 Pass by Result ..................................................................................................................................... 18 Pass by Value-Result.......................................................................................................................... 19 Pass by Reference (aliasing) .............................................................................................................. 20 Pass by Name...................................................................................................................................... 21 Binding ................................................................................................................................................... 22 Binding Times .................................................................................................................................... 22 Static Binding (Early binding) ........................................................................................................... 22
  • 4. Dynamic Binding (Late binding)....................................................................................................... 23Scope ....................................................................................................................................................... 23 Static Scope......................................................................................................................................... 23 Dynamic Scope ................................................................................................................................... 24Storage Classes........................................................................................................................................ 25 Auto Storage Class.............................................................................................................................. 25 Extern storage class ............................................................................................................................ 26 Register Storage Class ........................................................................................................................ 31 Static Storage Class............................................................................................................................. 31Storage Organization ............................................................................................................................. 32 Static Segment .................................................................................................................................... 32 Stack Segment .................................................................................................................................... 33 Heap Segment .................................................................................................................................... 35Shallow Copy versus Deep Copy........................................................................................................... 36
  • 5. DATA STRUCTURES AND ALGORITHMS MADE EASY
  • 6. ©www.CareerMonk.comFree Content Chapter 1 INTRODUCTIONIn this chapter, we will discuss the basic elements of algorithms. We will be using these while discussingthe algorithms in remaining chapters. If you are familiar with these, you can safely skip this chapter andstart from second chapter.VariablesBefore going to the definition of variables, let us relate them to old mathematical equations. All of us havesolved many mathematical equations since childhood. As an example, consider the below equation:We don’t have to worry about the use of above equation. The important thing that we need to understandis, the equation has some names ( and ) which hold values (data). That means, the ( and ) arethe place holders for representing data. Similarly, in computer science we need something for holding dataand are the facility for doing that.Data typesIn the above equation, the variables and can take any values like integral numbers ( , etc...), realnumbers ( etc…) or just and . To solve the equation, we need to relate them to kind of valuesthey can take and is the name being used in computer science for this purpose.A in a programming language is a set of data with values having predefined characteristics.Examples of data types are: integer, floating point unit number, character, string etc...Computer memory is all filled with zeros and ones. If we have a problem and wanted to code it, it’s verydifficult to provide the solution in terms of zeros and ones. To help users, programming languages andcompilers are providing the facility of data types.For example, takes bytes (actual value depends on compiler), takes bytes etc… What thissays is, in memory we are combining bytes ( bits) and calling it as integer. Similarly, we are combining bytes ( bits) and calling it as float. Same is the case with other data types also. A data type reduces thecoding effort. Basically, at the top level, there are two types of data types:  System defined data types (also called data types)  User defined data types9 Introduction | Variables
  • 7. ©www.CareerMonk.comFree ContentSystem defined data types (Primitive data types)Data types which are defined by system are called data types. The primitive data types which areprovided by many programming languages are: int, float, char, double, bool, etc…The number of bits allocated for each primitive data type depends on the programming languages, compilerand operating system. For the same primitive data type, different languages may use different sizes.Depending on the size of the data types the total available values (domain) will also changes.For example, “ ” may take bytes or bytes. If it takes bytes ( bits) then the total possible values are- to + (- -1). If it takes, bytes ( bits), then the possible values are between to (- -1). Same is the case with remaining data types too.User defined data typesIf the system defined data types are not enough then most programming languages allows the users todefine their own data types and we call them as user defined data types. Good example of user defined datatype are: structures in and classes in .For example, in the below case, we are combining many system defined data types and called it as userdefined data type with name “ ”. This gives more flexibility and comfort in dealing with computermemory. struct newType { int data1; int data 2; float data3; … char data; }Data StructureBased on the above discussion, once we have data in variables, we need some mechanism for manipulatingthat data to solve our problems. In computer science, a is a particular way of storing andorganizing data in a computer so that it can be used efficiently. That means, a is aspecialized format for organizing and storing data. General data structure types include arrays, files, linkedlists, stacks, queues, trees, graphs and so on.Depending on the organization of the elements, data structures are classified into two types: 1) Elements are stored in a sequential order. e.g. Arrays, linked list, : Linked Lists, Stacks and Queues.10 Introduction | Data Structure
  • 8. ©www.CareerMonk.comFree Content 2) : Elements of this data structure are stored in a non-linear order. : Trees and graphs.Abstract Data Types (ADT’s)Before defining abstract data types, let us consider the different view of system defined data types. We allknow that, by default, all primitive data types (int, float, et..) supports basic operations like addition,subtraction etc… The system is providing the implementations for the primitive data types. For userdefined data types also we need to define operations. The implementation for these operations can be donewhen we want to actually use them. That means, in general we define user defined data types along withtheir operations.To simplify the process of solving the problems, we generally combine the data structures along with theiroperations and are called (ADTs). An ADT consists of parts: 1. Declaration of data 2. Declaration of operationsCommonly used ADTs : Linked Lists, Stacks, Queues, Priority Queues, Binary Trees, Dictionaries,Disjoint Sets (Union and Find), Hash Tables, Graphs, and many other. For example, stack uses LIFO (Last-In-First-Out) mechanism while storing the data in data structures. The last element inserted into the stackis the first element that gets deleted. Common operations of it are: creating the stack, pushing an elementonto the stack, popping an element from stack, finding the current top of the stack, finding number ofelements in the stack etc...While defining the ADT’s we do not care about implementation details. They come in to picture only whenwe want to use them. Different kinds of ADT’s are suited to different kinds of applications, and some arehighly specialized to specific tasks. By the end of this book, we will go through all of them and you will bein a position to relate the data structures to the kind of problems they solve.Memory and Variables Address Memory Value 0 Memory Value 1 2 ... … … … …First let’s understand the way memory is organized in a computer. We can treat the memory as an array ofbytes. Each location is identified by an address (index to array). In general, the address is not a valid11 Introduction | Abstract Data Types (ADT’s)
  • 9. ©www.CareerMonk.comFree Contentmemory location. It is important to understand that the address of any byte (location) in memory is aninteger. In the below diagram value depends on the main memory size of the system.To read or write any location, CPU accesses it by sending its address to the memory controller. When wecreate a variable (for example, in : ), the compiler allocates a block of contiguous memory locationsand its size depends on the size of the variable. The compiler also keeps an internal tag that associates thevariable name with the address of the first byte allocated to it (sometimes called as ). Sowhen we want to access that variable like this: , the compiler knows where that variable is locatedand it writes the value . Address Memory Value 0 Memory Value 1 X 2 ... … … 2000 …Size of a Variable operator is used to find size of the variable (how much memory a variable occupies). For example,on some computers, ( ) gives the value . This means an integer needs contiguous bytes inmemory. If the address of would be , then the actual memory locations used by are: and .Address of a VariableIn language, we can get the address of a variable using operator ( ). The below code printsthe address of variable. In general, addresses are printed in hexadecimal as they are compact and also easyto understand if the addresses are big. int X; printf("The address is: %un", &X); Address Memory Value 0 Memory Value X 2 ... … … &XAddress of 2000 X is 2000 …12 Introduction | Memory and Variables
  • 10. ©www.CareerMonk.comFree ContentPointersPointers are also variables which can hold the address of another variable.Declaration of PointersTo declare a pointer, we have to specify the type of the variable it will point to. That means we need tospecify the type of the variable whose address it’s going to hold. The declaration is very simple. Let us seesome examples of pointer declarations below: int *ptr1; float *ptr2; unsigned int *ptr3; char *ptr4; void *ptr5;Here is a pointer that can point to an variable, can point to a , to an ,and to a . Finally is a pointer that can point to anything. These pointers are calledpointers, and there are some restrictions on what we can do with void pointers.Pointers UsageAs we said, pointers hold addresses. That means, we can assign the address of a variable to it. Let us considerthe below sample code: int X = 10; int *ptr = &X;Here, we first declare an integer named and initialize it to the value . Then we create a pointer tonamed and assign the address of to it. This is called, “ .” Acommon operation we can do with a pointer is what is called and it is a way to access thecontents of the memory that it points to. The indirection operator is represented by the asterisk symbol. Donot confuse this operator with the use of the same asterisk symbol in the declaration of pointers, they arenot the same thing. Address Memory Value &ptrAddress of 0 Memory Value ptr is 2 1 ptr 2 2000 … … &XAddress of X 2000 X is 2000 …13 Introduction | Pointers
  • 11. ©www.CareerMonk.comFree ContentIf we would like to access the contents of the memory where points to, we would do it like this:Let’s see a small code that shows pointer indirections. int X = 10; int *ptr = &X; printf("X contains the value %dn", X); printf("ptr points to %pn", ptr); printf("there lies the value %dn", *ptr); *ptr = 25; printf("now X contains the value %dn", X);Here we first declare and just like before. Then we print (which is ), followed by , i.e., thecontents of the variable which is an address; the address of . And finally we print , which is thevalue of the memory location where points to (again 10, since it points to the location occupied by thevariable in memory).Finally we change the contents of the location where points to by writing , this meansassign the value to wherever is pointing to. Note that when we do that, what actually happening ismodifying the value of . This is because, holds the address of , and changing the contents of thememory at that address changes the value of .One limitation of pointers, i.e. pointers that can point to any type, is that they cannot be . This is because of the fact that each variable type takes different amount of memory. On a -bit computer for example usually an int needs bytes, while a short bytes. So in order to read theactual value stored there, the compiler has to know how many consecutive memory locations to read inorder to get the full value.Pointer ManipulationAnother very useful thing we can do with pointers is to perform arithmetic operations on them. This mightbe obvious to the careful reader, since we said that pointers are just integers. However, there are a few smalldifferences on pointer arithmetic that make their use even more intuitive and easy. Try the following code: char *cptr = (char*)2; printf("cptr before: %p ", cptr); cptr++; printf("and after: %pn", cptr);We declare a pointer named and assign the address to it. We print the contents of the pointer (i.e.the address ), increment it, and print again. Sure enough the first time it prints and then , and that wasexactly what we expected. However try this one as well: int *iptr = (int*)2; printf("iptr before: %p ", iptr); iptr++;14 Introduction | Pointers
  • 12. ©www.CareerMonk.comFree Content printf("and after: %pn", iptr);Now the output, on my computer, is before: and after: Why does this pointer point to the address6 after incremented it by one and not to as the previous pointer? The answer lies with what we said aboutthe variables.An int is bytes on my computer. This means that if we have an int at the address , then that int occupiesthe memory locations and . So in order to access to the next int we have to look at the addressand . Thus when we add one to a pointer, it is not the same as adding one to any integer, it means give mea pointer to the next variable which for variables of type int, in this case, is bytes ahead.The reason that in the first example with the char pointer, the actual address after incrementing, was onemore than the previous address is because the size of char is exactly . So the next char can indeed be foundon the next address. Another limitation of void pointers is that we cannot perform arithmetic on them,since the compiler cannot know how many bytes ahead is the next variable located. So void pointers canonly be used to keep addresses that we have to convert later on to a specific pointer type, before using them.Arrays and PointersThere is a strong connection between arrays and pointers. So strong in fact, that most of the time we cantreat them as the same thing. The name of an array can be considered just as a pointer to the beginning of amemory block as big as the array. So for example, making a pointer point to the beginning of an array isdone in exactly the same way as assigning the contents of a pointer to another: short *ptr; short array[10]; ptr = array;and then we can access the contents of the array through the pointer as if the pointer itself was that array.For example this: is perfectly legal. Furthermore, we can treat the array itself as a pointer, forexample, is equivalent to In general is equivalent to .The only difference between an array, and a pointer to the beginning of an array, is that the compiler keepssome extra information for the arrays, to keep track of their storage requirements. For example if we get thesize of both an array and a pointer using the operator, sizeof(ptr) will give us how much space doesthe pointer itself occupies ( on my computer), while sizeof array will give us, the amount of spaceoccupied by the whole array (on my computer elements of bytes each).Dynamic Memory AllocationIn the earlier sections, we have seen that pointers can hold addressed of another variables. There is anotheruse of pointers: pointers can hold addresses of memory locations that do not have a specific compile-timevariable name, but are allocated dynamically while the program runs (sometimes such memory is called ).15 Introduction | Pointers
  • 13. ©www.CareerMonk.comFree ContentTo allocate memory during runtime, language provides us the facility interns of function. Thisfunction allocates the requested amount of memory, and returns a pointer to that memory. To deallocatethat block of memory, supports it by providing function. This function takes the pointer as anargument. For example, in the below code, an array of 5 integers is allocated dynamically, and then deleted. int count = 5; int *A = malloc(count * sizeof(int)); ……… free(arr);In this example, the calculates the amount of bytes we need to allocate for the array,by multiplying the number of elements, to the size of each element (i.e. the size of one integer).Function PointersLike data, executable code (including functions) also stored in memory. We can get the address of afunction. But the question is what type of pointers we use for that purpose?In general, we use function pointers and they store the address of functions. Using function pointers we cancall the function indirectly. But, function pointers manipulation has limitation: limited to assignment andindirection and cannot do arithmetic on function pointers. Because for function pointers there no ordering(functions can be stored anywhere in memory). The following example illustrates how to create and usefunction pointers. int (*fptr)(int); fptr = function1; printf("function1of 0 is: %dn", fptr(5)); fptr = function2; printf("function2 of 0 is: %dn", fptr(10));First we create a pointer that can point to functions accepting an as an argument and returning int,named . Then we make point to the , and proceed to call it through the pointer,to print the of . Finally, we change to point to , and call it again in exactly thesame manner, to print the of .Parameter Passing TechniquesBefore starting our discussion on parameter passing techniques, let us concentrate on the terminology weuse.Actual and Formal ParametersLet us assume that a function is called from another function . In this case, is called the “callerfunction” and is called the “called function or callee function”. Also, the arguments which sends to16 Introduction | Parameter Passing Techniques
  • 14. ©www.CareerMonk.comFree Contentare called actual arguments and the parameters of function are called formal arguments. In the belowexample, the is called from function. is the caller function and is the called function.Also, the arguments and are formal arguments and of function are actualarguments.int main(){ long i = 1; double j = 2; // Call func with actual arguments i and j. func( i, j );}// func with formal parameters param1 and param2.void func( long param1, double param2 ){}Semantics of Parameter PassingLogically, parameter passing uses the following semantics:  IN: Passes info from caller to . Formal arguments can take values from actual arguments, but cannot send values to actual arguments.  OUT: Callee writes values in the caller. Formal arguments can send values from actual arguments, but cannot take values from actual arguments.  IN/OUT: Caller tells callee value of variable, which may be updated by callee. Formal arguments can send values from actual arguments, and also can take values from actual arguments.Language Support for Parameter Passing Techniques Passing Technique Supported by Languages Pass by value Pass by result Pass by value-result , sometimes Pass by reference (achieves through pointers), Pass by nameNow, let us discuss the parameter passing techniques one by one.Pass by ValueThis method uses in-mode semantics. A formal parameter is like a new local variable that exists within thescope of the procedure/function/subprogram. Value of actual parameter is used to initialize the formal17 Introduction | Parameter Passing Techniques
  • 15. ©www.CareerMonk.comFree Contentparameter. Changes made to formal parameter get transmitted back to the caller. If pass by value isused then the formal parameters will be allocated on stack like a normal local variable. This method issometimes called as .Advantage of this method is that, it allows the actual arguments not to modify.In general the pass by value technique is implemented by copy and it has the following disadvantages:  Inefficiency in storage allocation  Inefficiency in copying value  For objects and arrays, the copy semantics are costlyExample: In the following example, main passes func two values: and . The function func receives copiesof these values and accesses them by the identifiers a and b. The function func changes the value of a.When control passes back to main, the actual values of and are not changed.void func (int a, int b){ a += b; printf("In func, a = %d b = %dn", a, b);}int main(void){ int x = 5, y = 7; func(x, y); printf("In main, x = %d y = %dn", x, y); return 0;}The output of the program is:In func, a = 12 b = 7In main, x = 5 y = 7Pass by ResultThis method uses out-mode semantics. A formal parameter is a new local variable that exists within thescope of the function. No value is transmitted from actual arguments to formal arguments. Just beforecontrol is transferred back to the caller, the value of the formal parameter is transmitted back to the actualparameter. This method is sometimes called asActual parameter be a variable. and are fine but not or .18 Introduction | Parameter Passing Techniques
  • 16. ©www.CareerMonk.comFree ContentParameter collisions can occur: That means, suppose let us assume that there is a function Ifthe two formal parameters in write had different names, which value should go into ? Order in whichactual parameters are copied determines their value.In general the pass by result technique is implemented by copy and it has the following disadvantages:  Inefficiency in storage allocation  Inefficiency in copying value  For objects and arrays, the copy semantics are costly  We cannot use the value of actual argument for initializing the formal argumentExample: Since does not support this technique, let us assume that the below syntax is not specific to anylanguage.In the following example, main uses two variable and . They both were passed to . Since this is passby result technique, the values of and will not be copied to formal arguments. As a result, the variables and of should be initialized. But in the function only is initialized. For this reason, the value of ais unknown, whereas the value of is . After the function execution, the values of a and b will be copiedto and .void func (int a, int b){ b = 5; a += b; printf("In func, a = %d b = %dn", a, b);}int main(void){ int x = 5, y = 7; func(x, y); printf("In main, x = %d y = %dn", x, y); return 0;}The output of the program is:In func, a = garbage value b = 5In main, x = garbage value y = 5Pass by Value-ResultThis method uses inout-mode semantics. It is a combination of Pass-by-Value and Pass-by-Result. Formalparameter is a new local variable that exists within the scope of the function. Value of actual parameter isused to initialize the formal parameter. Just before control is transferred back to the caller, the value of the19 Introduction | Parameter Passing Techniques
  • 17. ©www.CareerMonk.comFree Contentformal parameter is transmitted back to the actual parameter. This method is sometimes called as . shares with and . The disadvantage ofrequiring multiple storage parameters and time for copying values. Shares with Pass-by-Result the problemassociated with the order in which actual parameters are assigned.So this technique has some advantages and some disadvantages.Example: Since does not support this technique, let us assume that the below syntax is not specific to anylanguage.In the following example, main uses two variable and . They both were passed to . Since this is passby value-result technique, the values of and will be copied to formal arguments. As a result, thevariables and of will get and respectively.In the , the values a and b are modified to and respectively. After the function execution, thevalues of a and b will be copied to and . The disadvantage of this method is that, for each argument anew allocation is created.void func (int a, int b){ b = 5; a += b; printf("In func, a = %d b = %dn", a, b);}int main(void){ int x = 5, y = 7; func(x, y); printf("In main, x = %d y = %dn", x, y); return 0;}The output of the program is:In ,In ,Pass by Reference (aliasing)This technique uses inout-mode semantics. Formal parameter is an alias for the actual parameter. Changesmade to formal parameter get transmitted back to the caller through parameter passing. This method issometimes called as or .20 Introduction | Parameter Passing Techniques
  • 18. ©www.CareerMonk.comFree ContentThis method is efficient in both time and space.The disadvantage of this is aliasing:  Many potential scenarios can occur  Programs are not readableExample: In , the pointer parameters are initialized with pointer values when the function is called. Whenthe function is called, the actual values of the variables and are exchanged because they arepassed by reference.void swapnum(int *i, int *j){ int temp = i; i = j; j = temp;}int main(void){ int a = 10; int b = 20; swapnum(&a, &b); printf("A is %d and B is %dn", a, b); return 0;}The output is: A is 20 and B is 10Pass by NameRather than using pass-by-reference for input/output parameters, used the more powerfulmechanism of . In essence, you can pass in the symbolic " ", of a variable, whichallows it both to be accessed and updated.For example, to double the value of you can pass its name (not its value) into the following procedure.procedure double(x); real x;begin x := x * 2end;21 Introduction | Parameter Passing Techniques
  • 19. ©www.CareerMonk.comFree ContentIn general, the effect of pass-by-name is to textually substitute the argument expressions in a procedure callfor the corresponding parameters in the body of the procedure, e.g., double( ) is interpreted asTechnically, if any of the variables in the called procedure clash with the callers variables, they must berenamed uniquely before substitution.Implications of the mechanism: 1. The argument expression is re-evaluated each time the formal parameter is accessed. 2. The procedure can change the values of variables used in the argument expression and hence change the expressions value.BindingIn the earlier sections we have seen that every variable is associated with a memory location. At the toplevel, is the process of associating the and the thing it contains. For example, association ofvariable names to values they contain.Binding TimesBased on the time at which association happens, binding times can be one of the following:  Binding operators to operations (for example, to addition of numbers).  Binding data types to possible values (for example, “ ” to its range of values).  Associating algorithms and data structures to problem.  Binding a variable to data type.  Layout of whole program in memory (names of separate modules (libraries) are finalized.  Choice of physical addresses (e.g. static variables in are bound to memory cells at load time).  Binding variables to values in memory locations.Basically there are types of bindings: binding and binding.Static Binding (Early binding)Static binding occurs before runtime and doesn’t change during execution. This is sometimes called as earlybinding.Examples  Bindings of values to constants in  Bindings of function calls to function definitions in22 Introduction | Binding
  • 20. ©www.CareerMonk.comFree ContentDynamic Binding (Late binding)Dynamic binding occurs or changes at runtime. This is sometimes called as late binding.Examples  Bindings of pointer variables to locations  Bindings of member function calls to virtual member function definitions in C++ScopeA scope is a program section of maximal size in which no bindings change, or at least in which noredeclarations are permitted. The scope rules of a language determine how references to names areassociated with variables.Basically there are types of scoping techniques: scoping and scoping.Static Scope is defined in terms of the physical structure of the program. The determination of scopes canbe made by the compiler. That means, bindings are resolved by examining the program text. Enclosingstatic scopes (to a specific scope) are called its and the nearest static ancestor is called a .Variables can be hidden from a unit by having a “ ” variable with the same name. Ada andallow access to these (e.g. class_name:: name). Most compiled languages, and included, uses staticscope rules.Example-1: Static scope rules: Most closest nested rule used in blocksfor (...){ int i; {… { i = 5; } } ...}To resolve a reference, we examine the local scope and statically enclosing scopes until a binding is found.Example-2: Static scope in nested function calls. In the below code, with static scoping, the variableof takes the value of global variable value ( ).23 Introduction | Scope
  • 21. ©www.CareerMonk.comFree Contentint count=10;void func2(){ printf("In func2=%d”, count);}void func1(in){ int count = 20; func2();}int main(void){ funct1(); return 0;}Dynamic ScopeDynamic scope rules are usually encountered in interpreted languages. Such languages do not normallyhave type checking at compile time because type determination isnt always possible when dynamic scoperules are in effect.In dynamic scoping, binding depends on the flow of control at run time and the order in which functionsare called, refers to the closest active binding.If we relook at the second example of static scoping, the variable of takes the value ofvariable value ( ). This is because, during runtime the is called from which in turn calledfrom main. That means looks at the stack and starts searching in the back ward direction. func2() func1() main()Let us take another example. In the below code, the variable of takes the value ofint count=10; searches the stack invoid func3() reverse direction and find the{ count in funct1(). printf("In func3=%d”, count);}24 Introduction | Scope
  • 22. ©www.CareerMonk.comFree Contentvoid func2(){ func3();}void func1(in) func3(){ int count = 30; func2() func2(); func1()}int main(void) main(){ funct1(); return 0;}Note: For the above example, if we use scope then the variable of takes the value ofglobal variable ( ).Storage ClassesLet us now consider the storage classes in . The storage class determines the part of memory where storageis allocated for the variable or object and how long the storage allocation continues to exist. It alsodetermines the scope which specifies the part of the program over which a variable name is visible, i.e. thevariable is accessible by name. There are four storage classes in are automatic, register, external, andstatic.Auto Storage ClassThis is the default storage class in . Auto variables are declared inside a function in which they are to beutilized. Also, keyword (e.g. auto int number;) is used for declaring the auto variables. These arecreated when the function is called and destroyed automatically when the function is exited. This variableis therefore private(local) to the function in which they are declared. Variables declared inside a functionwithout storage class specification is, by default, an automatic variable.Any variable local to main will normally live throughout the whole program, although it is active only inmain. During recursion, the nested variables are unique auto variables. Automatic variables can also bedefined within blocks. In that case they are meaningful only inside the blocks where they are declared. Ifautomatic variables are not initialized they will contain garbage.Example:int main(){ int m=1000;25 Introduction | Storage Classes
  • 23. ©www.CareerMonk.comFree Content function2(); printf(“%dn”,m);}void function1(){ int m = 10; Output: printf(“%dn”,m); 10} 100void function2() 1000{ int m = 100; function1(); printf(“%dn”,m);}Extern storage classThese variables are declared outside any function. These variables are active and alive throughout the entireprogram. Also known as global variables and default value is zero. Unlike local variables they are accessedby any function in the program. In case local variable and global variable have the same name, the localvariable will have precedence over the global one. Sometimes the keyword extern used to declare thisvariable. It is visible only from the point of declaration to the end of the program.Example-1: The variable and are available for use in all three functionint number;float length=7.5;main(){ ... ...}funtion1(){ ... ...}funtion1(){ ... ...}Example-2: When the function references the variable , it will be referencing only its local variable,not the global one.26 Introduction | Storage Classes
  • 24. ©www.CareerMonk.comFree Contentint count;main(){ count=10; . . .. . .}funtion(){ int count=0; . . .. . . count=count+1;}Example-3: On global variables: Once a variable has been declared global any function can use it andchange its value. The subsequent functions can then reference only that new value.int x;int main(){ x=10; printf(“x=%dn”,x); printf(“x=%dn”,fun1()); printf(“x=%dn”,fun2()); printf(“x=%dn”,fun3());}int fun1() Output:{ x=10 x=x+10; x=20 return(x); x=1} x=30int fun2(){ int x; x=1; return(x);}int fun3(){ x=x+10; return(x);}Example-4: External declaration: As far as main is concerned, is not defined. So compiler will issue anerror message.27 Introduction | Storage Classes
  • 25. ©www.CareerMonk.comFree ContentThere are two ways to solve this issue: 1 Define before main. 2 Declare with the storage class extern in main before using it.int main(){ y=5; ... ...}int y;func1(){ y=y+1;}Example-5: External declaration: Note that extern declaration does not allocate storage space for variablesint main(){ extern int y; ... ...}func1(){ extern int y; ... ...}int y;Example-5: If we declare any variable as extern variable then it searches that variable either it has beeninitialized or not. If it has been initialized which may be either extern or static* then it is ok otherwisecompiler will show an error. For example:int main(){ extern int i; //It will search the initialization of variable i. printf("%d",i); return 0;}int i=2; //Initialization of variable i.28 Introduction | Storage Classes
  • 26. ©www.CareerMonk.comFree ContentOutput: 2Example-6: It will search the any initialized variable which may be static or extern.int main(){ extern int i; printf("%d",i); return 0;}extern int i=2; //Initialization of extern variable i.Output: 2Example-8: It will search the any initialized variable which may be static or extern.int main(){ extern int i; printf("%d",i); return 0;}static int i=2; //Initialization of static variable i.Output: 2Example-9: Variable i has declared but not initialized.int main(){ extern int i; printf("%d",i); return 0;}Output: Compilation error: Unknown symbol i.Example-10: A particular extern variable can be declared many times but we can initialize at only one time.For example:extern int i; //Declaring the variable i.int i=5; //Initializing the variable.extern int i; //Again declaring the variable i.int main(){ extern int i; //Again declaring the variable i.29 Introduction | Storage Classes
  • 27. ©www.CareerMonk.comFree Content printf("%d",i); return 0;}Output: 5Example-11:extern int i; //Declaring the variableint i=5; //Initializing the variable#include <stdio.h>int main(){ printf("%d",i); return 0;}int i=2; //Initializing the variableOutput: Compilation error: Multiple initialization variable i.Example-12: We cannot write any assignment statement globally.extern int i;int i=10; //Initialization statementi=5; //Assignment statementint main(){ printf("%d",i); return 0;}Output: Compilation errorNote: Assigning any value to the variable at the time of declaration is known as whileassigning any value to variable not at the time of declaration is known as .Example-13:extern int i;int main(){ i=5; //Assignment statement printf("%d",i); return 0;}30 Introduction | Storage Classes
  • 28. ©www.CareerMonk.comFree Contentint i=10; //Initialization statementOutput: 5Register Storage ClassThese variables are stored in one of the machine’s register and are declared using register keyword. e.g. register int count;Since register access are much faster than a memory access keeping frequently accessed variables in theregister lead to faster execution of program. Since only few variables can be placed in the register, it isimportant to carefully select the variables for this purpose. However, will automatically convert registervariables into non-register variables once the limit is reached. Don’t try to declare a global variable asregister. Because the register will be occupied during the lifetime of the program.Static Storage ClassThe value of static variables persists until the end of the program. It is declared using the keyword staticlike: static int x; static float y;It may be of external or internal type depending on the place of their declaration. Static variables areinitialized only once, when the program is compiled.Internal Static VariablesAre those which are declared inside a function? Scope of Internal static variables extends up to the end ofthe program in which they are defined. Internal static variables are almost same as auto variable except theyremain in existence (alive) throughout the remainder of the program. Internal static variables can be used toretain values between function calls. Internal static variable can be used to count the number of calls made to function.int main(){ int i; Output: for(i=1; i<=3; i++) X=1 stat(); X=2} X=3void stat(){ static int x=0;31 Introduction | Storage Classes
  • 29. ©www.CareerMonk.comFree Content x = x+1; printf(“x= %dn”,x);}External Static VariablesAn external static variable is declared outside of all functions and is available to all the functions in theprogram. An external static variable seems similar simple external variable but their difference is that staticexternal variable is available only within the file where it is defined while simple external variable can beaccessed by other files.Static FunctionStatic declaration can also be used to control the scope of a function. If you want a particular function to beaccessible only to the functions in the file in which it is defined and not to any function in other files,declare the function to be static.static int power(int x, int y){ ... ...}Storage OrganizationWhen we write a program and try executing it, lot of things happen. Now, let us try to understand whathappens internally. Any program we run has some memory associated with it. That memory is divided into parts as shown below. Storage organization is the process of binding values to memory locations. Heap Segment Stack Segment Data Segment Static Segment Code SegmentStatic SegmentAs shown above, the static storage is divided into two parts:32 Introduction | Storage Organization
  • 30. ©www.CareerMonk.comFree Content  In this part, the programs code is stored. This will not change throughout the execution of the program. In general, this part is made read-only and protected. Constants may also be placed in the static area depending on their type.  In simple terms, this part holds the global data. In this part, programs static data (except code) is stored. In general, this part is editable (like global variables and static variables come under this category). These includes the following: o Global variables o Numeric and string-valued constant literals o Local variables that retain value between calls (e.g., static variables)Stack SegmentSuppose if a language supports recursion, then the number of instances of a variable that may exist at theany time is unlimited (at least theoretically). In this case, static allocation is not useful.As an example, let us assume that a function is called from another function In the below code, the is having a local variable . After executing , if tries to get , then it should be able toget its old value. That means, it needs a mechanism for storing the current state of the function, so that onceit comes back from calling function it restores that context and uses its variables.A(){ int count=10; function(); count=20; . . .. . .}B(){ int b=0; . . .. . .}To solve these kind of issues, stack allocation is the used. When we call a , push a new (also called a ) onto the run-time stack, which is particular to the . Each frame canoccupy many consecutive bytes in the stack and may not be of a fixed size. When the functionreturns to the , the activation record of the callee is popped out. In general the activation recordstores the following information:  Local variables  Formal parameters  Any additional information needed for the activation.  Temporary variables33 Introduction | Storage Organization
  • 31. ©www.CareerMonk.comFree Content  Return addressA typical organization of a frame is the following: Next Activation Record, if not Stack Pointer top of stack Argument-1 : Argument- Dynamic Link Activation Record Return Address Static Link Local and temporary Frame Pointer variables Argument-1 : Previous Activation Record Argument-For example, if the program calls the function , calls , and calls , then at the time of thesecond call to , there will be frames in the stack in the following order: .Note that a should not make any assumptions about who is the caller because there may be manydifferent functions that call the same function. The frame layout in the stack should reflect this. When weexecute a function, its frame is located on top of the stack. The function does not have any knowledge aboutwhat the previous frames contain. There two things that we need to do though when executing a function:the first is that we should be able to pop-out the current frame of the callee and restore the caller frame.This can be done with the help of a pointer in the current frame, called the that points to theprevious frame (the callers frame). Thus all frames are linked together in the stack using dynamic links.This is called the . When we pop the callee from the stack, we simply set the stack pointerto be the value of the dynamic link of the current frame.The second thing that we need to do is, if we allow nested functions we need to be able to access thevariables stored in previous activation records in the stack. This is done with the help of theFrames linked together with static links form a . The static link of a function points to thelatest frame in the stack of the function that statically contains . If is not lexically contained in any otherfunction, its static link is NULL. For example, in the previous program, if called then the static link ofwill point to the latest frame of in the stack (which happened to be the previous frame in our example).34 Introduction | Storage Organization
  • 32. ©www.CareerMonk.comFree ContentNote that we may have multiple frames of in the stack, will point to the latest. Also notice that there isno way to call if there is no frame in the stack, since is hidden outside in the program.Before we create the frame for the callee, we need to allocate space for the callees arguments. Thesearguments belong to the callers frame, not to the callees frame. There is a (called ) thatpoints to the beginning of the frame.Heap SegmentIf we want to dynamically increase the temporary space (say, through pointers in ), then the and allocation methods are not enough. We need a separate allocation method for dealing this kind ofrequests. strategy is the one which addresses this issue. Heap allocation method requiredfor the dynamically allocated pieces of linked data structures and for dynamically resized objects.Heap is an area of memory which is dynamically allocated. Like a stack, it may grow and shrinks duringruntime. But unlike a stack it is not a (Last In First Out) which is more complicated to manage. Ingeneral, all programming languages implementation we will have both heap-allocated and stack allocatedmemory.How do we allocate memory for both?One simple approach is to divide the available memory at the start of the program into two areas: stack andheap.Heap Allocation MethodsHeap allocation is performed by searching the heap for available free space. Basically there are two types ofheap allocations.  Allocations were done automatically. For example, class instances are placed on the heap. Scripting languages and functional languages make extensive use of the heap for storing objects.  In this method, we need to explicitly tell the system to allocate the memory from heap. Examples include: o statements and/or functions for allocation and deallocation o malloc/free, new/deleteFragmentationsSometimes the small free blocks will get wasted without allocating to any process and we call such issue as . Basically there are two types of fragmentations.  If the block allocated is larger than required to hold a given object and the extra space is unused.35 Introduction | Storage Organization
  • 33. ©www.CareerMonk.comFree Content  In this case the unused space is composed of multiple blocks. No one piece of it may be large enough to satisfy some future request. That means, multiple unused blocks, but no one is large enough to be used.Heap Allocation AlgorithmsIn general, a linked list of free heap blocks are maintained and when a request is made for memory, then ituses one of the below techniques and allocates the memory.  select the first block in the list that is large enough to satisfy the given request  search the entire list for the smallest free block that is large enough to hold the objectIf an object is smaller than the block, the extra space can be added to the list of free blocks. When a block isfreed, adjacent free blocks are merged.Shallow Copy versus Deep CopyA of an object copies all of the member field values. This works well if the fields are values,but may not be what we want for fields that point to dynamically allocated memory. The pointer will becopied. But the memory it points to will not be copied. The field in both the original object and the copywill then point to the same dynamically allocated memory, which is not usually what you want. The defaultcopy constructor and assignment operator make shallow copies. copies all fields, and makes copies of dynamically allocated memory pointed to by the fields. Tomake a deep copy, we must write a copy constructor and overload the assignment operator, otherwise thecopy will point to the original, with disastrous consequences.36 Introduction | Shallow Copy versus Deep Copy

×