# Programming Methodology

Size: px
Start display at page:

Transcription

1 Spring 2009 Variables

2 2 Topics Components of a variable Name Assignment l value and r value Scope & Life time Arrays Constant variables

3 Programming language constructs 3 types statements blocks procedures/functions int foo(char* l) { int j, k; float x, y, z; j = 0; while (j < n) { x = 2.0 * y + z; } } main() { int m; m = foo(list); } variables expressions parameters

4 Variables and assignments 4 Components of a variable 1. name : identifier composed of letters 2. memory location : bound to the variable 3. current value : stored in the location 4. data type : static/dynamic binding 5. scope : static/dynamic 6. life time : interval during which a location is bound to the variable An assignment changes the contents of some components of a variable. float x; x = 1.5; //the type is a real number of value 1.5 x = 10; //now, the type is a real number of value 10.0

5 location (l value) and value (r value) 5 The location of a variable is regarded as a kind of value owned by the variable. We call the location the l value of the variable. To make a distinction, the real value of the variable is called the r value. Ex: char z = o ; // l value of z is the address of z, and r value is o A rule of assignments: The left hand side of an assignment should have the l value, and its right hand side should have the r value. float x; // create real variable x with the l value in which the r value is undefined float y = 4.1; // create real variable y with the r value defined by storing 4.1 to l value of y x = y; // store the r value of y into the l value of x y = y * 3.0; // store the r value of y times 3.0 into the l value of y If different variables have the same l value, it is called aliasing. Ex: char d; char & c = d; // c and d share the same location

6 Properties of l values and r values 6 referencing: the operation of getting the l value of a variable Ex: char* p = &c; dereferencing: the operation of going from a reference to the r value it refers In C++, the right hand side is always dereferenced once. char c, d; char *p, **q, **r; c = d; q = r; d = p; p = c; r = c; // OK! dereferenced once // OK! dereferenced once // error! dereferenced twice // error! no dereferencing necessary // error! no dereferencing sufficient

7 Properties of l values and r values 7 Some expressions, such as id, array reference and dereference, have both l values and r values. All other expressions have r values only. So they can NOT appear on the left hand side of assignments. 4.5 = 10.1; // illegal integers have no l values jane = y; // illegal strings have no l values y + 1 = a[i]; // illegal arithmetic expressions have no l values x = 10.1; // legal id expressions have l values a[i] = y + 1 // legal array references have l values employee.name = jane // legal *p = foo(x,y) // legal dereference expressions have l values foo(x,y) = 1.1; // maybe legal, maybe illegal gnu c++ says error: non lvalue in assignment

8 Graphical notation for variables 8 name Location that can contain an ordinary data value Location that can contain a reference (address) value Location that can contain a reference reference value

9 Graphical notation for variables 9 char c = w ; char d = c; c d w w copy char& e = d; e alias char* p = &c; p char** q = &p; q copy char** r = q; r const char cc = w cc w

10 Name conflicts 10 In languages, a name can be used to mean several different objects. Ex) Ford: : a name of a man, a car, or a company Using the same name to represent different objects in different places causes a name conflict and potentially ambiguity of the language. But, name conflicts are often necessary to improve naturalness of a language and readability/writability. Ford drives a car. They work for the Ford. How do we know which Ford means which in each sentence? She drives a Ford. Ford1 drives a car. They work for the Ford2. She drives a Ford3. OK. no more naming conflict! So, the meaning is clearer. But do you like it?

11 Scope 11 Ambiguity due to naming conflicts can be resolved by associating names with the environments where each name is defined. Jane in Ohio, Jane in Maine, Jane in Virginia In a programming language, a scope is a program environment in which names are defined or declared. procedures and blocks (Pascal, C/C++), lambda expressions (Scheme) Through a declaration within some scope, a name is bound to a variable with certain attributes, and the variable is called a bound variable. A variable which is not bound in the scope is called a free variable.

12 Scope 12 { // Beginning of a new environment/scope int a[10]; int i; char c; // declarations of three names c // a reference to c : bound to a character variable a[i] // references to a and i : bound to integer variables x // a reference to the free variable x within this scope } // End of a scope c // The name no longer represents a character variable. // Then, what is it now? A binding of a name is visible and effective inside the scope where the name is declared. The idea of a scope is to limit the boundary of a declaration of a name. Outside the boundary of a declaration, that declaration and binding should not be visible.

13 Example: scopes in mathematics 13 scope 1 The notion of a scope also appears in mathematics. Let x be the amount of salary that Susan receives every month, and y be the price of the new car she wants to have. Then, the time that it takes for her to buy the car is y/x months. Now, let x be the amount of money that John wastes every day, and y be the total amount of money he currently has. Then, the time that it takes before he goes bankrupt is y/x days. declarations references scope of x scope of y scope of z A declaration of x makes x a bound variable. scope 2 Existential,, and universal,, quantifiers provide a formal notion of scope. ( x ( y f(x,y) ) ( z g(x,y,z) ) ) declarations free variable

14 Principle in binding of variables A bound variable in an expression can be renamed uniformly to another variable that does not appear in the expression without changing the meaning of the expression. Example: x ( yf(x,y)) = x ( vf(x,v)) = y ( v f(y,v)) = y ( x f(y,x)) y ( y f(y,y)) The declaration y in y ( yf(y,y)) is vacuous and invisible to f(y,y) in ( yf(y,y)) because y supercedes y. 14

15 Using the principle 15 What does this mean to a programming language? code 1 int x; { int * y; x + *y; } code 2 int x; { int * v; x + *v; } code 3 int y; { int * v; y + *v; } code 4 int y; { int * x; y + *x; } code 5 int y; { int * y; y + *y; } code 1 = code 2 = code 3 = code 4!= code5 useful for detecting programming assignment copies?

16 Static vs. dynamic scopes 16 Each language has its own rules that tell us where to find the declaration for a name in a program. The rules are called the scope rules (or scope regime). Scope rules can be categorized largely into two kinds: static scope (Fortran, Pascal, C/C++, Scheme, Common Lisp) dynamic scope (pure Lisp, APL, SmallTalk) static scope A scope of a variable is the region of text for which a specific binding of the variable is visible. Therefore, the connection between references and declarations can be made lexically, based on the text of the program. At compile time, a free variable is bound by a declaration in textually enclosing scopes/environments.

17 Static vs. dynamic scopes 17 dynamic scope The connection between references and declarations cannot be determined lexically since, in general, a variable is not declared until run time, and may even be redeclared as the program executes. At run time, a free variable in a procedure is bound by a declaration in the environment from which the procedure is called. rarely adopted by most existing languages since it generally has more disadvantages (difficult to read, more expensive ) than static scoping Ex: Output of foo(10)? int n = 2; bar(int k) { print k+n; } foo(int m) { int n = 5; bar(m); } static scoping 12 int n = 2; bar(int k) { print k+n; } foo(int m) { int n = 5; bar(m); } dynamic scoping 15 foo(int m) { int n = 5; bar(m); } call chain bar(int k) { print k+n; }

18 Life time 18 Life time of a variable is the interval of time for which a specific binding of the variable is active. cf: scope During the life time of a variable, a variable is bound to memory storage. Let x be a simple/automatic variable declared inside a scope S. The life time of x begins when program execution enters the scope S, and ends when execution leaves the scope. Only when the binding of x is visible, x is a live variable. A global variable is kind of a simple variable whose scope is global.

19 Life time 19 Let x be a static variable declared inside a scope S. The life time of x begins when program execution starts, and ends when program execution terminates. Even when the binding of x is not visible, x remains a live variable. C++ extern int omnipresent; // Global, nonstatic variable int f() { static int die_hard; // Static variable, as it says int short_lived; // Automatic variable f() } main() { f() } What are the life time and scope of die_hard? What are the life times and scopes of short_lived and omnipresent? What happens to them when f is recursively called?

20 20 Topics Components of a variable Name Assignment l value and r value Scope & Life time Arrays Constant variables

21 Array variables 21 In some languages like Pascal, when you declare x, y : array [1..5] of integer; the compiler creates not only the storage for 5 integers, but also a pointer to its beginning address. x When we have an array assignment y = x; the whole contents of the array x are copied to the location of the array y. y copy write (x[1],y[1]); y[1] = 10; write (x[1],y[1]); x[1] = 0; write (x[1],y[1]);

22 Array variables 22 But in Java/C++, an array is really a pointer. Java arrays int[] a = { 10, 20, 30, 40 }; int[] b = { 50, 60, 70, 80 }; int[] c = new int[4]; So, arrays and pointers can be mixed. Thus, after b = a, we should have a b If this is Java, it is later collected safely as garbage. If this is C++, it is memory leak What happens to this array? b = a; // legal Java arrays c = a; // legal System.out.println(a[1] + b[1] + c[1]); b[1] = 1; System.out.println(a[1] + b[1] + c[1]); a[1] = 99; System.out.println(a[1] + b[1] + c[1]);?

23 Array variables 23 In C++, the result is slightly different since C++ has explicit pointer types while Java does not. C++ arrays int a[] = { 10, 20, 30, 40 }; // static array int b[] = { 50, 60, 70, 80 }; // static array int *c = new int[4]; // array pointer (dynamic array) In C++, array assignment is illegal. (element wise copies needed) b = a; // illegal c = a; // legal cout << a[1] << c[1]; c[1] = 99; cout << a[1] << c[1];? g++: ISO C++ forbids assignments of arrays Visual C++: left hand side must have l value Static arrays use stack memory; their pointers cannot change dynamically. c = a: r value of a (address of the array) is store to l value of pointer c. So in this respect, Java arrays act more likely as C++ array pointers.

24 Multidimensional arrays 24 Declaration of 2 dimensional and 3 dimensional arrays float a[3][4]; int b[4][5][2]; The elements of a are shown as a table. a[0][0] a[0][1] a[0][2] a[0][3] a[1][0] a[1][1] a[1][2] a[1][3] a[2][0] a[2][1] a[2][2] a[2][3] Two schemes to represent a or b in programming languages Mapping onto an 1 dimensional array adopted by many languages like Fortran (up to 7 dimensions possible) Using the array of arrays adopted by Java/C/C++

25 Mapping onto an 1 D array 25 The elements in a matrix/cube are mapped sequentially to an 1 dimensional contiguous space in the memory. Row/Column major mapping converting an m n 2 D array into an 1 D array with length m n by collecting elements by rows/columns a 00 a 01 a 02 a 10 a 11 a 12 a 20 a 21 a 22 a 00 a 10 a 20 a 01 a 11 a 21 a 02 a 12 a 22 &a[] Example: Fortran90 column major a ij a ij row major column major Mem[α+i w n+j w] Mem[α+j w n+i w] x 11 x 21 x 31 x 12 x 22 x 32 x 13 x 23 x 33 integer x(3,3) = (/ 4,5,9,0,9,6,2,8,3 /) x(2,3) offset from the beginning = 7 byte address = x+28 a 00 a 01 a 02 a 10 a 11 a 12 a 20 a 21 a 22

26 Using array of arrays 26 Java and C++ basically have only 1 D arrays. Conceptually, their multidimensional arrays are simulated with arrays of arrays. (Maybe this is why we write a[i][j] instead of a[i,j]) Ex: a 2 D array is viewed as an 1 D array of rows each of which is also represented as an 1 D array. a, b, c, d e, f, g, h i, j, k, l x.length = 3 stored as four 1-D arrays x = [x[0], x[1], x[2]] x[0] = [a, b, c, d] x[1] = [e, f, g, h] x[1] = [i, j, k, l] x[0].length = x[1].length = x[2].length = 4 Physically, their static arrays are stored to 1 D memory in rowmajor order. int x[3][4]; // static 2 D array x a b c d e f g h i j k l x[0] x[1] x x[0] x[1] x[2] a b c d e f g h i j k l x[2]+1 x[1]+5 x[2][1] *(x[2]+1)

27 Mixing arrays and pointers in C++ 27 Code int v[3][2]; int *t = (int *)(v + 1); // v[1] int *s = (int *) v + 1; // v[0]+1, *v+1 or &v[0][1] int *u = v + 1; // error: cannot convert int(*)[2] into int* int **p = &t; int **w = v; // error: cannot convert int(*)[2] into int** int **q = p + 1; int *r = ++*p; p[0][1] // *(t+1) p[1][0] // runtime error: segment fault *q // runtime error: segment fault Graphical notations v s p r t

28 Dynamic multidimensional arrays 28 Create a dynamic array of dimension for a pointer z. int ***z; How about this? error: cannot convert int(*)[5][9] into int*** Explicit arrays of arrays to simulate a 3 D array. create z = new int[4][5][9]; clean up z = new int**[4]; if (z!= NULL) for (int i = 0; i < 4; i++) { z[i] = new int*[5]; if (z[i]!= NULL) for (int j = 0; j < 5; j++) z[i][j] = new int[9]; } z[i][j][k] = // access it like ordinary 3 D array for (int i = 0; i < 4; i++) { for (int j = 0; j < 5; j++) { delete [] z[i][j]; z[i][j] = 0; } delete [] z[i]; z[i] = 0; } delete [] z; z = 0;

29 Constant variables? 29 Typical way to specify a name for a constant C/C++ provides a special construct const to declare a variable whose value is constant during program execution. A constant variable must be invariable. cf: #define Ten 10 x = Ten * y; // x = 10 * y const int ten = 10; x = ten * y; // x = 10 * y ten = x + 1; // error: const var ten cannot be assigned a value Ten = x + 1; // error: left hand side of = must have l value It may be viewed as a static variable with a constant value. No dynamic memory alloc/dealloc is needed whether it is visible or not.

30 Constant variables 30 Comparison with #define d names Const vars have scopes, so their visibility can be controlled. They can be bound to specific types: const float, const char*,... They can be applied to diverse constructs. const struct { }, const int foo() { } const for pointer types = int x, y; // ordinary variables const int ten = 10; // a constant variable const int * tp = &ten; // a pointer to a constant variable tp = &x; // error! How about tp = &ten again here? OK int const * tq = &ten; // a pointer to a constant variable *tq = y; // error! How about *tq = 20? OK int * const tr = &x; // a constant pointer to a variable tr = &ten; // error! How about tr = &y? error *tr = 20; // Is this OK? yes How about *tr = y? OK const int * const ts = &ten; // a constant pointer to a constant variable const int * const tt = &x; // error! ts = &x; // error! How about ts = &ten again or *ts = y? error

31 Advantages over ordinary variables 31 safer code (safeguard enforced by the compiler) better quality code Option 1: use static memory for ten instead of runtime stack efficient memory utilization especially for recursion Option 2: use immediate addressing for ten C code const int ten = 10; m = m + tin; n = n + ten; void foo( &x) { x = } int main() { const int ten = 10; int tin = 10; foo(ten) // foo should not change ten ten = // Compile error! Did you mean tin? The compiler may propagate ten=10. So this is error Assembly code load r1,<m> load r2,<tin> add r1,r1,r2 load r3,<n> add r3,r3,10

### CS 314 Principles of Programming Languages

CS 314 Principles of Programming Languages Lecture 15: Review and Functional Programming Zheng (Eddy) Zhang Rutgers University March 19, 2018 Class Information Midterm exam forum open in Sakai. HW4 and

### CSE 307: Principles of Programming Languages

1 / 26 CSE 307: Principles of Programming Languages Names, Scopes, and Bindings R. Sekar 2 / 26 Topics Bindings 1. Bindings Bindings: Names and Attributes Names are a fundamental abstraction in languages

### Chapter 5. Names, Bindings, and Scopes

Chapter 5 Names, Bindings, and Scopes Chapter 5 Topics Introduction Names Variables The Concept of Binding Scope Scope and Lifetime Referencing Environments Named Constants 1-2 Introduction Imperative

### The Compiler So Far. CSC 4181 Compiler Construction. Semantic Analysis. Beyond Syntax. Goals of a Semantic Analyzer.

The Compiler So Far CSC 4181 Compiler Construction Scanner - Lexical analysis Detects inputs with illegal tokens e.g.: main 5 (); Parser - Syntactic analysis Detects inputs with ill-formed parse trees

### CS 330 Lecture 18. Symbol table. C scope rules. Declarations. Chapter 5 Louden Outline

CS 0 Lecture 8 Chapter 5 Louden Outline The symbol table Static scoping vs dynamic scoping Symbol table Dictionary associates names to attributes In general: hash tables, tree and lists (assignment ) can

### Informatica 3 Syntax and Semantics

Informatica 3 Syntax and Semantics Marcello Restelli 9/15/07 Laurea in Ingegneria Informatica Politecnico di Milano Introduction Introduction to the concepts of syntax and semantics Binding Variables Routines

### COS 140: Foundations of Computer Science

COS 140: Foundations of Computer Science Variables and Primitive Data Types Fall 2017 Introduction 3 What is a variable?......................................................... 3 Variable attributes..........................................................

SE352b Software Engineering Design Tools W3: Programming Paradigms Feb. 3, 2005 SE352b, ECE,UWO, Hamada Ghenniwa SE352b: Roadmap CASE Tools: Introduction System Programming Tools Programming Paradigms

### CS 415 Midterm Exam Spring 2002

CS 415 Midterm Exam Spring 2002 Name KEY Email Address Student ID # Pledge: This exam is closed note, closed book. Good Luck! Score Fortran Algol 60 Compilation Names, Bindings, Scope Functional Programming

### Note 3. Types. Yunheung Paek. Associate Professor Software Optimizations and Restructuring Lab. Seoul National University

Note 3 Types Yunheung Paek Associate Professor Software Optimizations and Restructuring Lab. Seoul National University Topics Definition of a type Kinds of types Issues on types Type checking Type conversion

### Programming Languages Third Edition. Chapter 7 Basic Semantics

Programming Languages Third Edition Chapter 7 Basic Semantics Objectives Understand attributes, binding, and semantic functions Understand declarations, blocks, and scope Learn how to construct a symbol

### Outline. Java Models for variables Types and type checking, type safety Interpretation vs. compilation. Reasoning about code. CSCI 2600 Spring

Java Outline Java Models for variables Types and type checking, type safety Interpretation vs. compilation Reasoning about code CSCI 2600 Spring 2017 2 Java Java is a successor to a number of languages,

### G Programming Languages - Fall 2012

G22.2110-003 Programming Languages - Fall 2012 Lecture 4 Thomas Wies New York University Review Last week Control Structures Selection Loops Adding Invariants Outline Subprograms Calling Sequences Parameter

### Type Bindings. Static Type Binding

Type Bindings Two key issues in binding (or associating) a type to an identifier: How is type binding specified? When does the type binding take place? N. Meng, S. Arthur 1 Static Type Binding An explicit

### CSE 307: Principles of Programming Languages

CSE 307: Principles of Programming Languages Variables and Constants R. Sekar 1 / 22 Topics 2 / 22 Variables and Constants Variables are stored in memory, whereas constants need not be. Value of variables

### 9/7/17. Outline. Name, Scope and Binding. Names. Introduction. Names (continued) Names (continued) In Text: Chapter 5

Outline Name, Scope and Binding In Text: Chapter 5 Names Variable Binding Type bindings, type conversion Storage bindings and lifetime Scope Lifetime vs. Scope Referencing Environments N. Meng, S. Arthur

### Pointer Basics. Lecture 13 COP 3014 Spring March 28, 2018

Pointer Basics Lecture 13 COP 3014 Spring 2018 March 28, 2018 What is a Pointer? A pointer is a variable that stores a memory address. Pointers are used to store the addresses of other variables or memory

### Chapter 6. Structured Data Types. Topics. Structured Data Types. Vectors and Arrays. Vectors. Vectors: subscripts

Topics Chapter 6 Structured Data Types Vectors Arrays Slices Associative Arrays Records Unions Lists Sets 2 Structured Data Types Virtually all languages have included some mechanisms for creating complex

### Informal Semantics of Data. semantic specification names (identifiers) attributes binding declarations scope rules visibility

Informal Semantics of Data semantic specification names (identifiers) attributes binding declarations scope rules visibility 1 Ways to Specify Semantics Standards Documents (Language Definition) Language

### Chapter 5 Names, Binding, Type Checking and Scopes

Chapter 5 Names, Binding, Type Checking and Scopes Names - We discuss all user-defined names here - Design issues for names: -Maximum length? - Are connector characters allowed? - Are names case sensitive?

### Attributes, Bindings, and Semantic Functions Declarations, Blocks, Scope, and the Symbol Table Name Resolution and Overloading Allocation, Lifetimes,

Chapter 5 Basic Semantics Attributes, Bindings, and Semantic Functions Declarations, Blocks, Scope, and the Symbol Table Name Resolution and Overloading Allocation, Lifetimes, and the Environment Variables

### The role of semantic analysis in a compiler

Semantic Analysis Outline The role of semantic analysis in a compiler A laundry list of tasks Scope Static vs. Dynamic scoping Implementation: symbol tables Types Static analyses that detect type errors

### The SPL Programming Language Reference Manual

The SPL Programming Language Reference Manual Leonidas Fegaras University of Texas at Arlington Arlington, TX 76019 fegaras@cse.uta.edu February 27, 2018 1 Introduction The SPL language is a Small Programming

### Names, Scope, and Bindings

Names, Scope, and Bindings COMS W4115 Prof. Stephen A. Edwards Spring 2007 Columbia University Department of Computer Science What s In a Name? Name: way to refer to something else variables, functions,

### Data Types (cont.) Subset. subtype in Ada. Powerset. set of in Pascal. implementations. CSE 3302 Programming Languages 10/1/2007

CSE 3302 Programming Languages Data Types (cont.) Chengkai Li Fall 2007 Subset U = { v v satisfies certain conditions and v V} Ada subtype Example 1 type Digit_Type is range 0..9; subtype IntDigit_Type

### COS 140: Foundations of Computer Science

COS 140: Foundations of Variables and Primitive Data Types Fall 2017 Copyright c 2002 2017 UMaine School of Computing and Information S 1 / 29 Homework Reading: Chapter 16 Homework: Exercises at end of

### Names, Bindings, Scopes

Names, Bindings, Scopes Variables In imperative l Language: abstractions of von Neumann machine Variables: abstraction of memory cell or cells Sometimes close to machine (e.g., integers), sometimes not

### Programming Languages Third Edition. Chapter 10 Control II Procedures and Environments

Programming Languages Third Edition Chapter 10 Control II Procedures and Environments Objectives Understand the nature of procedure definition and activation Understand procedure semantics Learn parameter-passing

### Binding and Variables

Binding and Variables 1. DEFINITIONS... 2 2. VARIABLES... 3 3. TYPE... 4 4. SCOPE... 4 5. REFERENCES... 7 6. ROUTINES... 9 7. ALIASING AND OVERLOADING... 10 8. GENERICS AND TEMPLATES... 12 A. Bellaachia

### CS 314 Principles of Programming Languages. Lecture 13

CS 314 Principles of Programming Languages Lecture 13 Zheng Zhang Department of Computer Science Rutgers University Wednesday 19 th October, 2016 Zheng Zhang 1 CS@Rutgers University Class Information Reminder:

### Homework #3 CS2255 Fall 2012

Homework #3 CS2255 Fall 2012 MULTIPLE CHOICE 1. The, also known as the address operator, returns the memory address of a variable. a. asterisk ( * ) b. ampersand ( & ) c. percent sign (%) d. exclamation

### Pointers. 1 Background. 1.1 Variables and Memory. 1.2 Motivating Pointers Massachusetts Institute of Technology

Introduction to C++ Massachusetts Institute of Technology ocw.mit.edu 6.096 Pointers 1 Background 1.1 Variables and Memory When you declare a variable, the computer associates the variable name with a

### CPSC 3740 Programming Languages University of Lethbridge. Data Types

Data Types A data type defines a collection of data values and a set of predefined operations on those values Some languages allow user to define additional types Useful for error detection through type

### COP4020 Programming Languages. Subroutines and Parameter Passing Prof. Robert van Engelen

COP4020 Programming Languages Subroutines and Parameter Passing Prof. Robert van Engelen Overview Parameter passing modes Subroutine closures as parameters Special-purpose parameters Function returns COP4020

### Semantic Analysis. Outline. The role of semantic analysis in a compiler. Scope. Types. Where we are. The Compiler Front-End

Outline Semantic Analysis The role of semantic analysis in a compiler A laundry list of tasks Scope Static vs. Dynamic scoping Implementation: symbol tables Types Static analyses that detect type errors

### CSC 533: Organization of Programming Languages. Spring 2005

CSC 533: Organization of Programming Languages Spring 2005 Language features and issues variables & bindings data types primitive complex/structured expressions & assignments control structures subprograms

### Names, Scope, and Bindings

Names, Scope, and Bindings COMS W4115 Prof. Stephen A. Edwards Fall 2007 Columbia University Department of Computer Science What s In a Name? Name: way to refer to something else variables, functions,

### Semantic Processing. Semantic Errors. Semantics - Part 1. Semantics - Part 1

Semantic Processing The Lexer and Parser Found lexical and syntax errors Built Abstract Syntax Tree Now!Find semantic errors.!build information about the program. Later!Generate IR Code!Optimize IR Code!Generate

### G Programming Languages Spring 2010 Lecture 4. Robert Grimm, New York University

G22.2110-001 Programming Languages Spring 2010 Lecture 4 Robert Grimm, New York University 1 Review Last week Control Structures Selection Loops 2 Outline Subprograms Calling Sequences Parameter Passing

### Semantic Analysis. Outline. The role of semantic analysis in a compiler. Scope. Types. Where we are. The Compiler so far

Outline Semantic Analysis The role of semantic analysis in a compiler A laundry list of tasks Scope Static vs. Dynamic scoping Implementation: symbol tables Types Statically vs. Dynamically typed languages

### CS 415 Midterm Exam Spring SOLUTION

CS 415 Midterm Exam Spring 2005 - SOLUTION Name Email Address Student ID # Pledge: This exam is closed note, closed book. Questions will be graded on quality of answer. Please supply the best answer you

### Programming Languages, Summary CSC419; Odelia Schwartz

Programming Languages, Summary CSC419; Odelia Schwartz Chapter 1 Topics Reasons for Studying Concepts of Programming Languages Programming Domains Language Evaluation Criteria Influences on Language Design

### CSCI312 Principles of Programming Languages!

CSCI312 Principles of Programming Languages! Scope Xu Liu ! 4.1 Syntactic Issues! 4.2 Variables! 4.3 Scope! 4.4 Symbol Table! 4.5 Resolving References! 4.6 Dynamic Scoping! 4.7 Visibility! 4.8 Overloading!

### Name, Scope, and Binding. Outline [1]

Name, Scope, and Binding In Text: Chapter 3 Outline [1] Variable Binding Storage bindings and lifetime Type bindings Type Checking Scope Lifetime vs. Scope Referencing Environments N. Meng, S. Arthur 2

### CS558 Programming Languages

CS558 Programming Languages Fall 2016 Lecture 3a Andrew Tolmach Portland State University 1994-2016 Formal Semantics Goal: rigorous and unambiguous definition in terms of a wellunderstood formalism (e.g.

### Answer: Early binding generally leads to greater efficiency (compilation approach) Late binding general leads to greater flexibility

Quiz Review Q1. What is the advantage of binding things as early as possible? Is there any advantage to delaying binding? Answer: Early binding generally leads to greater efficiency (compilation approach)

### Semantic Analysis. How to Ensure Type-Safety. What Are Types? Static vs. Dynamic Typing. Type Checking. Last time: CS412/CS413

CS412/CS413 Introduction to Compilers Tim Teitelbaum Lecture 13: Types and Type-Checking 19 Feb 07 Semantic Analysis Last time: Semantic errors related to scopes Symbol tables Name resolution This lecture:

Chapter 10 Pointers and Dynamic Arrays Copyright 2016 Pearson, Inc. All rights reserved. Learning Objectives Pointers Pointer variables Memory management Dynamic Arrays Creating and using Pointer arithmetic

### The PCAT Programming Language Reference Manual

The PCAT Programming Language Reference Manual Andrew Tolmach and Jingke Li Dept. of Computer Science Portland State University September 27, 1995 (revised October 15, 2002) 1 Introduction The PCAT language

### Design Issues. Subroutines and Control Abstraction. Subroutines and Control Abstraction. CSC 4101: Programming Languages 1. Textbook, Chapter 8

Subroutines and Control Abstraction Textbook, Chapter 8 1 Subroutines and Control Abstraction Mechanisms for process abstraction Single entry (except FORTRAN, PL/I) Caller is suspended Control returns

### CSE 504. Expression evaluation. Expression Evaluation, Runtime Environments. One possible semantics: Problem:

Expression evaluation CSE 504 Order of evaluation For the abstract syntax tree + + 5 Expression Evaluation, Runtime Environments + + x 3 2 4 the equivalent expression is (x + 3) + (2 + 4) + 5 1 2 (. Contd

### Principles of Programming Languages Topic: Scope and Memory Professor Louis Steinberg Fall 2004

Principles of Programming Languages Topic: Scope and Memory Professor Louis Steinberg Fall 2004 CS 314, LS,BR,LTM: Scope and Memory 1 Review Functions as first-class objects What can you do with an integer?

### 1 Lexical Considerations

Massachusetts Institute of Technology Department of Electrical Engineering and Computer Science 6.035, Spring 2013 Handout Decaf Language Thursday, Feb 7 The project for the course is to write a compiler

### 1 Terminology. 2 Environments and Static Scoping. P. N. Hilfinger. Fall Static Analysis: Scope and Types

and Computer Sciences Computer Science Division CS 164 Fall 2006 P. N. Hilfinger Static Analysis: Scope and Types 1 Terminology Programs, in general, are simply collections of definitions of terms, which

### Arrays. Returning arrays Pointers Dynamic arrays Smart pointers Vectors

Arrays Returning arrays Pointers Dynamic arrays Smart pointers Vectors To declare an array specify the type, its name, and its size in []s int arr1[10]; //or int arr2[] = {1,2,3,4,5,6,7,8}; arr2 has 8

### Data Types. Outline. In Text: Chapter 6. What is a type? Primitives Strings Ordinals Arrays Records Sets Pointers 5-1. Chapter 6: Data Types 2

Data Types In Text: Chapter 6 1 Outline What is a type? Primitives Strings Ordinals Arrays Records Sets Pointers Chapter 6: Data Types 2 5-1 Data Types Two components: Set of objects in the type (domain

### Run-time Environments - 3

Run-time Environments - 3 Y.N. Srikant Computer Science and Automation Indian Institute of Science Bangalore 560 012 NPTEL Course on Principles of Compiler Design Outline of the Lecture n What is run-time

### Low-Level C Programming. Memory map Pointers Arrays Structures

Low-Level C Programming Memory map Pointers Arrays Structures Memory Map 0x7FFF_FFFF Binaries load at 0x20000 by default Stack start set by binary when started Stack grows downwards You will need one stack

### Programming Languages

Programming Languages Tevfik Koşar Lecture - VIII February 9 th, 2006 1 Roadmap Allocation techniques Static Allocation Stack-based Allocation Heap-based Allocation Scope Rules Static Scopes Dynamic Scopes

### The Compiler So Far. Lexical analysis Detects inputs with illegal tokens. Overview of Semantic Analysis

The Compiler So Far Overview of Semantic Analysis Adapted from Lectures by Profs. Alex Aiken and George Necula (UCB) Lexical analysis Detects inputs with illegal tokens Parsing Detects inputs with ill-formed

### Lexical Considerations

Massachusetts Institute of Technology Department of Electrical Engineering and Computer Science 6.035, Spring 2010 Handout Decaf Language Tuesday, Feb 2 The project for the course is to write a compiler

### Chapter 10 Pointers and Dynamic Arrays. GEDB030 Computer Programming for Engineers Fall 2017 Euiseong Seo

Chapter 10 Pointers and Dynamic Arrays 1 Learning Objectives Pointers Pointer variables Memory management Dynamic Arrays Creating and using Pointer arithmetic Classes, Pointers, Dynamic Arrays The this

### LECTURE 14. Names, Scopes, and Bindings: Scopes

LECTURE 14 Names, Scopes, and Bindings: Scopes SCOPE The scope of a binding is the textual region of a program in which a name-to-object binding is active. Nonspecifically, scope is a program region of

### Procedure and Object- Oriented Abstraction

Procedure and Object- Oriented Abstraction Scope and storage management cs5363 1 Procedure abstractions Procedures are fundamental programming abstractions They are used to support dynamically nested blocks

### Lecture 4 Memory Management

Lecture 4 Memory Management Dr. Wilson Rivera ICOM 4036: Programming Languages Electrical and Computer Engineering Department University of Puerto Rico Some slides adapted from Sebesta s textbook Lecture

### Data Types In Text: Ch C apter 6 1

Data Types In Text: Chapter 6 1 Outline What is a type? Primitives Strings Ordinals Arrays Records Sets Pointers 2 Data Types Two components: Set of objects in the type (domain of values) Set of applicable

### CS 230 Programming Languages

CS 230 Programming Languages 11 / 20 / 2015 Instructor: Michael Eckmann Questions/comments? Chapter 6 Arrays Pointers Today s Topics We all know what arrays are. Design issues Legal types for subscripts

### CS 242. Fundamentals. Reading: See last slide

CS 242 Fundamentals Reading: See last slide Syntax and Semantics of Programs Syntax The symbols used to write a program Semantics The actions that occur when a program is executed Programming language

### Pointers. Memory. void foo() { }//return

Pointers Pointers Every location in memory has a unique number assigned to it called it s address A pointer is a variable that holds a memory address A pointer can be used to store an object or variable

### Lecture 16: Static Semantics Overview 1

Lecture 16: Static Semantics Overview 1 Lexical analysis Produces tokens Detects & eliminates illegal tokens Parsing Produces trees Detects & eliminates ill-formed parse trees Static semantic analysis

### Properties of an identifier (and the object it represents) may be set at

Properties of an identifier (and the object it represents) may be set at Compile-time These are static properties as they do not change during execution. Examples include the type of a variable, the value

### C++ PROGRAMMING LANGUAGE: DYNAMIC MEMORY ALLOCATION AND EXCEPTION IN C++. CAAM 519, CHAPTER 15

C++ PROGRAMMING LANGUAGE: DYNAMIC MEMORY ALLOCATION AND EXCEPTION IN C++. CAAM 519, CHAPTER 15 This chapter introduces the notion of dynamic memory allocation of variables and objects in a C++ program.

### G Programming Languages - Fall 2012

G22.2110-003 Programming Languages - Fall 2012 Lecture 2 Thomas Wies New York University Review Last week Programming Languages Overview Syntax and Semantics Grammars and Regular Expressions High-level

### Storage. Outline. Variables and updating. Copy vs. Ref semantics Lifetime. Dangling References Garbage collection

Storage 1 Variables and updating Outline Copy vs. Ref semantics Lifetime Local and global variables Heap variables Persistent variables Dangling References Garbage collection 2 Variables and Updating Variable:

### Programmiersprachen (Programming Languages)

2016-05-13 Preface Programmiersprachen (Programming Languages) coordinates: lecturer: web: usable for: requirements: No. 185.208, VU, 3 ECTS Franz Puntigam http://www.complang.tuwien.ac.at/franz/ps.html

### Chapter 5 Names, Bindings, Type Checking, and Scopes

Chapter 5 Names, Bindings, Type Checking, and Scopes Names Variables The Concept of Binding Scope and Lifetime Type Checking Referencing Environments Named Constants Names Used for variables, subprograms

### Lecture 7: Type Systems and Symbol Tables. CS 540 George Mason University

Lecture 7: Type Systems and Symbol Tables CS 540 George Mason University Static Analysis Compilers examine code to find semantic problems. Easy: undeclared variables, tag matching Difficult: preventing

### MIDTERM EXAM (Solutions)

MIDTERM EXAM (Solutions) Total Score: 100, Max. Score: 83, Min. Score: 26, Avg. Score: 57.3 1. (10 pts.) List all major categories of programming languages, outline their definitive characteristics and

### Chapter 9 Subprograms

Chapter 9 Subprograms We now explore the design of subprograms, including parameter-passing methods, local referencing environment, overloaded subprograms, generic subprograms, and the aliasing and problematic

### Compilers. Type checking. Yannis Smaragdakis, U. Athens (original slides by Sam

Compilers Type checking Yannis Smaragdakis, U. Athens (original slides by Sam Guyer@Tufts) Summary of parsing Parsing A solid foundation: context-free grammars A simple parser: LL(1) A more powerful parser:

### Functional Programming. Pure Functional Programming

Functional Programming Pure Functional Programming Computation is largely performed by applying functions to values. The value of an expression depends only on the values of its sub-expressions (if any).

### Comp 11 Lectures. Mike Shah. June 26, Tufts University. Mike Shah (Tufts University) Comp 11 Lectures June 26, / 57

Comp 11 Lectures Mike Shah Tufts University June 26, 2017 Mike Shah (Tufts University) Comp 11 Lectures June 26, 2017 1 / 57 Please do not distribute or host these slides without prior permission. Mike

### public class Foo { private int var; public int Method1() { // var accessible anywhere here } public int MethodN() {

Scoping, Static Variables, Overloading, Packages In this lecture, we will examine in more detail the notion of scope for variables. We ve already indicated that variables only exist within the block they

### Heap, Variables, References, and Garbage. CS152. Chris Pollett. Oct. 13, 2008.

Heap, Variables, References, and Garbage. CS152. Chris Pollett. Oct. 13, 2008. Outline. Dynamic Allocation. Variables and Constants. Aliases and Problems. Garbage. Introduction. On Wednesday, we were talking

### Topic IV. Parameters. Chapter 5 of Programming languages: Concepts & constructs by R. Sethi (2ND EDITION). Addison-Wesley, 1996.

References: Topic IV Block-structured procedural languages Algol and Pascal Chapters 5 and 7, of Concepts in programming languages by J. C. Mitchell. CUP, 2003. Chapter 5 of Programming languages: Concepts

### CS 161 Exam II Winter 2018 FORM 1

CS 161 Exam II Winter 2018 FORM 1 Please put your name and form number on the scantron. True (A)/False (B) (28 pts, 2 pts each) 1. The following array declaration is legal double scores[]={0.1,0.2,0.3;

### Review. Outline. Array Pointer Object-Oriented Programming. Fall 2017 CISC2200 Yanjun Li 1. Fall 2017 CISC2200 Yanjun Li 2

Review Fall 2017 CISC2200 Yanjun Li 1 Outline Array Pointer Object-Oriented Programming Fall 2017 CISC2200 Yanjun Li 2 1 Computer Fall 2017 CISC2200 Yanjun Li 3 Array Arrays are data structures containing

### procedure definition (or declaration - some make a distinction, we generally won t), e.g., void foo(int x) {... }

Parameters Terminology: procedure invocation, e.g., (in different language notations) foo(a*8) x:=goo(19,a) call hoo() actual parameters, e.g., a*8 is an actual parameter of the above inv ocation of foo

### [0569] p 0318 garbage

A Pointer is a variable which contains the address of another variable. Declaration syntax: Pointer_type *pointer_name; This declaration will create a pointer of the pointer_name which will point to the

### PIC 10A Pointers, Arrays, and Dynamic Memory Allocation. Ernest Ryu UCLA Mathematics

PIC 10A Pointers, Arrays, and Dynamic Memory Allocation Ernest Ryu UCLA Mathematics Pointers A variable is stored somewhere in memory. The address-of operator & returns the memory address of the variable.

### Pointers, Dynamic Data, and Reference Types

Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation The new operator The delete operator Dynamic Memory Allocation for Arrays 1 C++ Data Types simple

### Short Notes of CS201

#includes: Short Notes of CS201 The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with < and > if the file is a system

### Operating Systems CMPSCI 377, Lec 2 Intro to C/C++ Prashant Shenoy University of Massachusetts Amherst

Operating Systems CMPSCI 377, Lec 2 Intro to C/C++ Prashant Shenoy University of Massachusetts Amherst Department of Computer Science Why C? Low-level Direct access to memory WYSIWYG (more or less) Effectively

### Please refer to the turn-in procedure document on the website for instructions on the turn-in procedure.

1 CSE 131 Winter 2013 Compiler Project #2 -- Code Generation Due Date: Friday, March 15 th 2013 @ 11:59pm Disclaimer This handout is not perfect; corrections may be made. Updates and major clarifications

### What have we learned about when we learned about function parameters? 1-1

What have we learned about when we learned about function parameters? 1-1 What have we learned about when we learned about function parameters? Call-by-Value also known as scalars (eg. int, double, char,

### Expressions and Assignment

Expressions and Assignment COS 301: Programming Languages Outline Other assignment mechanisms Introduction Expressions: fundamental means of specifying computations Imperative languages: usually RHS of