Presentation is loading. Please wait.

Presentation is loading. Please wait.

Concepts of programming languages Names, Bindings, and Scopes

Similar presentations


Presentation on theme: "Concepts of programming languages Names, Bindings, and Scopes"— Presentation transcript:

1 Concepts of programming languages Names, Bindings, and Scopes
Chapter 5 Names, Bindings, and Scopes Lec. 12 Lecturer: Dr. Emad Nabil

2 local and global scope in Python
x = 0 def outer(): x = 1 def inner(): x = 2 print("inner:", x) inner() print("outer:", x) outer() print("global:", x) # inner: 2 # outer: 1 # global: 0

3 local and global scope in Python
x = 0 def outer(): x = 1 def inner(): nonlocal x x = 2 print("inner:", x) inner() print("outer:", x) outer() print("global:", x) # inner: 2 # outer: 2 # global: 0 Python 3 introduced the nonlocal  keyword that allows you to assign to variables in an outer, but non-global, scope. An example will illustrate what I mean.

4 local and global scope in Python
x = 0 def outer(): x = 1 def inner(): global x x = 2 print("inner:", x) inner() print("outer:", x) outer() print("global:", x) # inner: 2 # outer: 1 # global: 2

5 Assume dynamic scope void sub1() { int a, b; . . . 1
} /* end of sub1 */ void sub2() { int b, c; sub1(); } /* end of sub2 */ void main() { int c, d; sub2(); } /* end of main */ Point Referencing Environment 1) a and b of sub1, c of sub2, d of main, (c of main and b of sub2 are hidden) 2) b and c of sub2, d of main, (c of main is hidden) 3) c and d of main

6 Referencing Environments
Chapter 5 Topics Introduction Names Variables The Concept of Binding Scope Scope and Lifetime Referencing Environments Named Constants Copyright © 2012 Addison-Wesley. All rights reserved.

7 Named Constants A named constant is a variable that is bound to a value only when it is bound to storage Advantages: readability and modifiability The binding of values to named constants can be either static (called manifest constants) or dynamic Manifest واضح Copyright © 2012 Addison-Wesley. All rights reserved.

8 Named Constants binding of values
Ada, C++, and Java: expressions of any kind, dynamically bound binding of values Dynamic-Run Time Static –Compilation Time Value bound at run time Value bound at compile time (const) C++, (final) Java, (readonly) C# C#(const) Copyright © 2012 Addison-Wesley. All rights reserved.

9 Named Constants Named constants in java
100 is written only one time and can’t be changed Named Constants Named constants in java

10 Named constants in java
public static void main(String[] args) { Scanner sc= new Scanner(System.in); int y=sc.nextInt(); final int x=2*y; System.out.println(x); } True: Value of x id Dynamically bound

11 Named Constants C++ example OK: Value Dynamically bound int y;
cin >> y; const int x = 2 * y; x++; cout << x; Syntax Error

12 Named Constants Error, need initialization C++ example
bound to a value only when it is bound to storage C++ example const int x; X=5; cout << x;

13 Named Constants In C# language Error const int x; x = 3; Error
int a=4, b=5; const int y=a+b; OK const int y=5 Must be initialized when declared Value bound at compile time

14 C# readonly variables can be changed only inside constructor
ok Named Constants class Program { public readonly int x =5; public readonly int y; Program() int a = int.Parse(Console.ReadLine()); y = a + 1; y++; } public void f() y++ static void Main(string[] args) OK OK error error

15 Summary Case sensitivity and the relationship of names to special words represent design issues of names Variables are characterized by the sextuples: name, address, value, type, lifetime, scope Binding is the association of attributes with program entities Scalar variables are categorized as: static, stack dynamic, explicit heap dynamic, implicit heap dynamic Strong typing means detecting all type errors Copyright © 2012 Addison-Wesley. All rights reserved.

16 Concepts of programming languages Chapter 6: Data Types Lec: 12 Lecturer Dr Emad Nabil

17 Chapter 6 Topics Introduction Primitive Data Types
Character String Types Array Types Pointer and Reference Types Type Checking Strong Typing Type Equivalence Theory and Data Types Copyright © 2012 Addison-Wesley. All rights reserved.

18 Introduction A data type defines a collection of data objects and a set of predefined operations on those objects A descriptor is the collection of the attributes of a variable An object represents an instance of a user-defined (abstract data) type One design issue for all data types: What operations are defined and how are they specified? Copyright © 2012 Addison-Wesley. All rights reserved.

19 Primitive Data Types Almost all programming languages provide a set of primitive data types Primitive data types: Those not defined in terms of other data types Some primitive data types are just reflections of the hardware (ex: int  4 bytes) Copyright © 2012 Addison-Wesley. All rights reserved.

20 Primitive Data Types: Integer
Almost always an exact reflection of the hardware so the mapping is trivial Java’s signed integer sizes: byte, short, int, long There exists another unsigned 4 types Copyright © 2012 Addison-Wesley. All rights reserved.

21 Primitive Data Types: Floating Point
Model real numbers, but only as approximations Languages for scientific use support at least two floating-point types e.g., float and double IEEE Floating-Point Standard 754 =±  Fraction × 2Exponent Copyright © 2012 Addison-Wesley. All rights reserved.

22 (0.2)10 = (0.001100110011001100110011)2 approximately 0* 2-1 +
( )2 = 0* 2-1 + 0* 2-2 + 1* 2-3 + 1* …..=

23 Primitive Data Types: Complex
Some languages support a complex type, e.g., C99, Fortran, and Python Each value consists of two floats, the real part and the imaginary part (in Python): (7 + 3j), where 7 is the real part and 3 is the imaginary part Copyright © 2012 Addison-Wesley. All rights reserved.

24 z = complex(2, -3) print(z) z = complex(1) z = complex('5-9j') z1 = complex(2, -3) z2 = complex('5-9j') print(z1+z2) (7-12j) (2-3j) (1+0j) (5-9j)

25 Primitive Data Types: Decimal
For business applications (money) Essential to COBOL C# offers a decimal data type Store a fixed number of decimal digits, in coded form (BCD), each digit represented in about 4 bits Advantage: accuracy Disadvantages: limited range, wastes memory, C# Decimal range ≅10^(+/-28) C# Double range ≅ 10^(+/-300).  Decimal digit BCD 8 4 2 1 3 5 6 7 9 Double - 64 bit (15-16 significant digits) Decimal bit (28-29 significant digits)

26 Primitive Data Types: Boolean
Simplest of all Range of values: two elements, one for “true” and one for “false” Could be implemented as bits, but often as bytes Advantage: readability Copyright © 2012 Addison-Wesley. All rights reserved.

27 Primitive Data Types: Character
ASCII American Standard Code for Information Interchange 2^7 (= 128) distinct combinations The last bit (8th) is used for avoiding errors as parity bit. Mainly for English extended ASCII" or "8-bit ASCII (2^8 = 256 characters). Some people started using the 8th bit (the bit used for parity) to encode more characters to support their language solves the problem for languages that are based on the Latin alphabet (like French) Unicode UTF-8 UTF-16 UTF-32 UTF-8: minimum 8 bits. UTF-16: minimum 16 bits. UTF-32: minimum and maximum 32 bits. UTF-8, used by websites (over 90%), uses one byte for the first 128 code points, and up to 4 bytes for other characters. UTF-16 is using 16-bit encoding for the Basic Multilingual Plane (less than 65,536 code points) , and a 4-byte encoding for the other charchters. Languages Like Greek, Russian, Polish, Chinese. The latest version contains a repertoire of 136,755 characters covering 139 modern and historic scripts (June 2017) C# and java and others support Unicode 8, 16 Fortran supports Unicode 32 starting with 2003

28 Array Types An array is a homogeneous set of data elements in which an individual element is identified by its position in the group of elements, relative to the first element. Copyright © 2012 Addison-Wesley. All rights reserved.

29 Array Design Issues What types are legal for subscripts?
Are subscripting expressions in element references range checked? When are subscript ranges bound? When does allocation take place? Are ragged or rectangular multidimensional arrays allowed, or both? What is the maximum number of subscripts? Can array objects be initialized? Are any kind of slices supported? Copyright © 2012 Addison-Wesley. All rights reserved.

30 Array Indexing Indexing (or subscripting) is a mapping from indices to elements array_name (index_value_list)  an element Index Syntax Fortran and Ada use parentheses Ada ex: Sum := Sum + B(I); Most other languages use brackets Copyright © 2012 Addison-Wesley. All rights reserved.

31 Arrays Index (Subscript) Types
FORTRAN, C++, C#, Java: integer only Index range checking - C, C++, Perl, and Fortran do not specify range checking - Java, C#, Python specify range checking - In Ada, the default is to require range checking, but it can be turned off

32 Range Checking In Python
x=[1,2,3] for i in range(10): print(x[i]) 1 2 3 IndexError: list index out of range

33 Subscript Binding and Array Categories
Static array Fixed stack-dynamic array stack-dynamic array Fixed heap-dynamic array Heap-dynamic arrays array

34 Subscript Binding and Array Categories
1 Static array: subscript ranges are statically bound and storage allocation is static (before run-time) Advantage: efficiency (no dynamic allocation) C++ ex: static char s[100]; Static array subscript binding Statically bound storage allocation static @load time @Data Segment Size Fixed

35 Subscript Binding and Array Categories
2 Fixed stack-dynamic array: subscript ranges are statically bound, but the allocation is done at declaration or elaboration time(when execution reaches the code to which the declaration is found) Advantage: space efficiency Disadvantage: time allocation and deallocation C++ ex: void foo() { int arr[7]; /* ... */ } Fixed stack-dynamic array subscript binding Statically bound @Compilation Time storage allocation Dynamically bound @Elaboration Time @Stack Size Fixed

36 Subscript Binding and Array Categories (continued)
3 Stack-dynamic: subscript ranges are dynamically bound and the storage allocation is dynamic (at Elaboration time) Advantage: flexibility (the size of an array need not be known until the array is to be used) Hint :In Java, C++, and C#, variables defined in methods are by default stack dynamic. void foo(int n) { int sarr[n]; /* ... */ } Get(List_Len); declare List : array (1..List_Len) of Integer; begin . . . end; Stack-dynamic array subscript binding dynamically bound @Elaboration Time storage allocation @Stack Size Fixed C99 allows that. Ada example

37 Subscript Binding and Array Categories (continued)
4 Fixed heap-dynamic array: similar to fixed stack-dynamic: storage binding is dynamic but fixed after allocation (i.e., binding is done when requested and storage is allocated from heap, not stack) Example in C++ int n; Cin>>n; Int * arr= new int[n]; Fixed heap-dynamic array subscript binding dynamically bound @Run Time storage allocation @Run Time - (when user request allocation) @Heap Size Fixed after allocation

38 Subscript Binding and Array Categories (continued)
5 Heap-dynamic array: binding of subscript ranges and storage allocation is dynamic and can change any number of times Advantage: flexibility (arrays can grow or shrink during program execution) In C#, Java, Perl, JavaScript, Python, .. Heap-dynamic array subscript binding dynamically bound @Run Time storage allocation @Heap Size Variable – can be changed after allocation

39 5 Heap-dynamic arrays Perl @list=(1,2,3,4,5); 6,7); @list=(); Python: a = [1.25, 233, , 0, ‐1] Now list value is (1,2,3,4,5,6,7) List is empty C# also provides generic heap-dynamic arrays through List object, ex: List<String> stringList = new List<String>(); stringList.Add("Michael"); Java includes a generic class similar to C#, named ArrayList. It is different from C#’s List in that subscripting is not supported—get and set methods must be used to access the elements.

40 Heap-dynamic arrays implementation
5 Heap-dynamic arrays implementation Linked list Allocate adjacent storage Allocation and deallocation fast Slow because of copying overhead when growing Speed of string operations Slow, jumping to links storage Big, because of links size small The already used method No yes

41 Subscript Binding and Array Categories
Static array Fixed stack-dynamic array stack-dynamic array Fixed heap-dynamic array Heap-dynamic arrays array


Download ppt "Concepts of programming languages Names, Bindings, and Scopes"

Similar presentations


Ads by Google