PROCEDURES, METHODS AND FUNCTIONS
|
|
- Valentine Moody
- 5 years ago
- Views:
Transcription
1 Cosc 2P90 PROCEDURES, METHODS AND FUNCTIONS (c) S. Thompson, M. Winters 1
2 Procedures, Functions & Methods The are varied and complex rules for declaring, defining and calling procedures, methods and functions Focus Parameter passing Types, effects and side-effects Storage allocation Different calling mechanisms and effects on reliability (c) S. Thompson, M. Winters 2
3 Parameters Formal parameters Found in declaration of routine E.g. int myfunc( int parama, int paramb ) Actual parameter Found in the call of the function E.g. myfunc( 1, 2 ); Example: C++ swap void swap(int& first, int& second) { int intermediate; intermediate = first; first = second; second = intermediate; } // swap swap( high, low); swap( left, right ); Procedural abstraction Allows you to think at a higher level (c) S. Thompson, M. Winters 3
4 Methods Found in object-oriented languages Exist as a component of a class target object implicit parameter bk1.deposit(6); vs deposit(bk1,6); Access to non-local data Discouraged in procedures In methods access to target object member data ok Self reference (this, self) privmethod(); vs this.privmethod(); Class methods (a.k.a. static methods) Act the same as regular functions (c) S. Thompson, M. Winters 4
5 Parameter Passing 3 modes for parameter passing in - Info goes into a procedure out Info is returned from a procured update info is passed into a procedure and modified implementations In call-by-value, call-by-constant-value, call-by-reference-constant Out call-by-result In/Out call-by-value-result call-by-reference call-by-name (c) S. Thompson, M. Winters 5
6 In Parameters Call-by-value Pascal, C++, C, Java formal is copy of actual int total(int val) { int sum = 0; while (val > 0) { sum += val; val--; } return sum; }// total modifying the parameter (c) S. Thompson, M. Winters 6
7 In Parameters call-by-constant-value Ada, FORTRAN 90 call-by-value but formal is a constant function total(val : in Integer) return Integer is sum : Integer := 0; count : Integer := val; explicit copy begin while count > 0 loop sum := sum + count; count := count + 1; end loop; return sum; end total; (c) S. Thompson, M. Winters 7
8 In Parameters call-by-reference Large structures are expensive to copy by value Pascal, C++, C# formal is reference to actual no protection call-by-reference-constant Ada, FORTRAN 90, C++ call-by-reference but formal is declared constant C++ float sum(const Matrix& m) { } (c) S. Thompson, M. Winters 8
9 In Parameters value vs constant-value vs reference-constant call-by-value max reference value copy val reference value max reference value call-by-constant-value val value copy call-by-reference-constant max reference copy value val reference (c) S. Thompson, M. Winters 9
10 Out Parameters call-by-result Ada, C# formal is uninitialized local value copied to actual at exit procedure read_negative(neg_number : out Integer) is number : Integer; begin get(number); while number >= 0 loop put_line( number not negative, try again ); get(number); end loop; neg_number := number; end read_negative; Actual out parameters require an l-value In C# actual parameters require out keyword e.g. int i; read_negative( out i ); Algol W address of actual computed at exit, instead of entry (c) S. Thompson, M. Winters 10
11 Update Parameters call-by-value-result Ada formal is copy with copy back to actual at exit procedure update(balance : in out Integer) is transaction : Integer; begin for j in loop get(transaction); balance := balance + transaction; end loop; end update; (c) S. Thompson, M. Winters 11
12 Update Parameters call-by-reference Pascal procedure update(var balance : Integer); C++ void update(int& balance); C# void update( ref int balance ); value-result vs reference No difference to the end-ser Aliasing actual in inherited scope and parameter same actual as multiple parameters expression parameters? Pascal, Ada, C++ require l-value Fortran, PL/1 allowed variables through a local copy Const & in C++ allows this (c) S. Thompson, M. Winters 12
13 Update Parameters currentacc reference value call-by-value-result copy out balance reference value copy in currentacc reference value call-by-reference copy balance reference value (c) S. Thompson, M. Winters 13
14 Java call-by-value (basic types) cannot modify primitive type parameters object variables are references reference passed object can be modified, but cannot change to different object (c) S. Thompson, M. Winters 14
15 Java Example static void test( int i ) { i += 4; System.out.println( i ); } static void test2( Point p ) { p = new Point( 1, 2 ); System.out.println( p.tostring() ); } static void test3( Point p ) { p.setlocation( 1, 2 ); System.out.println( p.tostring() ); } public static void main(string[] args) { int j = 4; test(j); System.out.println( j ); Point t2 = new Point( 100, 200 ); Point t3 = new Point( 100, 200 ); test2( t2 ); test3( t3 ); System.out.println( t2.tostring() ); System.out.println( t3.tostring() ); (c) S. Thompson, M. Winters 15
16 C call-by-value only can pass addresses (& operator) procedure treats as pointer void swap(int *first, int *second) { int intermidiate; intermidiate = *first; *first = *second; *second = intermidiate; } swap(&higher, &lower); Disadvantages NULL pointers (c) S. Thompson, M. Winters 16
17 Call-by-name Straight textual substitution ALGOL 60 actual parameter is unevaluated at call, but evaluated upon each reference seldom used in imperative languages used in functional languages (lazy evaluation) C preprocessor functions #define max( a, b ) ( (a) > (b)? (a) : (b) ) a = max( random(), 5.0f ); spot the bug! (c) S. Thompson, M. Winters 17
18 Languages & Mechanisms Language value constantvalue referenceconstant Mechanism result reference valueresult name Algol 60 * * Fortran 90 *??? Pascal * * C * C++ * * * Ada (scalars) * * * Ada (others)????? Java * (c) S. Thompson, M. Winters 18
19 Comparison var element : Integer; a : array [1.. 2] of Integer; procedure whichmode(x :? mode Integer); begin a[1] := 6; element := 2; x := x + 3; end; begin a[1] := 1; a[2] := 2; element := 1; whichmode(a[element]); (c) S. Thompson, M. Winters 19
20 Comparison Mechanism Result a[1] a[2] element call-by-value call-by-value-result (Algol W) call-by-value-result call-by-reference call-by-name (c) S. Thompson, M. Winters 20
21 Overloading Overloading refers to having multiple procedures or methods with the same name must differ in signature Example class Writer { void print( int c ) { }; void print( float f ) { }; void print( char c ) { }; } Most languages don t allow overloading to only differ by return type Other languages have special cases (Pascal) to achieve this Not available to the programmer (c) S. Thompson, M. Winters 21
22 Default Parameters An alternative to overloading Provide a default value for parameters can omit actual parameters must be last parameters procedure inc (item: in out integer; by: in integer := 1; mul: in integer :=1) is begin item := item*mul+by; end inc; : inc(i); Useful to reduce complexity of functions and interfaces (c) S. Thompson, M. Winters 22
23 Named Parameters Normally position is how we associate formal and actual parameters Fortran, PL/1, Ada, Python also have named parameters Associate the formal with the actual by name instead of position inc(by=>2,mul=>3,item=>i); inc(i,mul=>3); This leads to easier code to read Myfunc( 1, 4, test ) vs. Myfunc( height: 1, width: 4, displaystring: test ) Related to enums vs bool argument as parameters (c) S. Thompson, M. Winters 23
24 Functions A procedure which returns a value differentiation, e.g. none in C, ALGOL 60 Association with mathematical function Specifying result assignment to function name (Algol 60, Pascal, FORTRAN) return statement (C, Java) Result can be considered extra result parameter Return type simple type ALGOL 60, Java, Pascal but also references structured type Ada, C, C++, FORTRAN 90, Algol 68 Order of evaluation a = b() + c() Usually not defined in language, up to compiler side effects Modifying parameters side effects Ada in out/out not permitted on functions C++ const (c) S. Thompson, M. Winters 24
25 Examples Fortran 90 FUNCTION TWICE(A) INTEGER TWICE INTEGER A TWICE = A + A END FUNCTION TWICE Algol 60 integer procedure twice(a); value a; integer a; twice := a + a Java int twice(int a) { return a + a; }// twice Pascal function twice(a : Integer):Integer; begin twice := a + a end; {twice} C++ int twice(int a) const { return a + a; }// twice Ada function twice(a : in Integer) begin return a + a; end twice; return Integer is (c) S. Thompson, M. Winters 25
26 Properties (not in text) In many O-O class to provide proper encapsulation class members are exposed through accessors & mutators class myclass { private int myvar; public int getmyvar() { return myvar; } public void setmyvar(int i) { myvar = i; } } Newer languages have introduced properties as an intermediate between fields and methods Acts like a field Allows validation of data Properties clearly represent what data is required for an object Used for automated serialization Found in python, C#, Delphi Can be implemented in C++ (c) S. Thompson, M. Winters 26
27 Properties Example C# class MyClass { private int myvar; } public int MyVar { get { return myvar; } set { myvar = value; } } MyClass obj = new MyClass(); obj.myvar = 5; func( obj.myvar ); (c) S. Thompson, M. Winters 27
28 Operators Operators use infix, functions use prefix a+b vs. add(a,b) functions define new operations declaring new operators really functions with different syntax Ada: function + (today : in Day; n : in Integer) return Day is begin return Day val((day pos(today) + n) rem 7); end; C++ Day operator+(day today, int n) const { } choice of operator existing operator symbols other symbols (usually not permitted) precedence rules (c) S. Thompson, M. Winters 28
29 Storage Management storage for local variables static pre-allocation - load-time binding efficient access size of each item known at compile time no data item has multiple simultaneous occurrences no recursion FORTRAN (c) S. Thompson, M. Winters 29
30 Storage Management Stack storage management Used in block-structured languages Reference Binding at block entry, de-allocation at exit Uses a stack of activation records (AR) Storage only for locals of active methods Code generated requires additional statements to bind references Addresses as offsets Useful if all local variables are known at compile time Some hardware has special support to speed this up (c) S. Thompson, M. Winters 30
31 Stack-based example program Main(output); var b, d : Integer; procedure z; var e, f : Integer; begin end {z}; procedure y; var g, h : Integer; begin z; end {y}; begin y; z; end. int d, b; void z() { int e, f; } void y() { int g,h; z(); } int main() { y(); z(); } (c) S. Thompson, M. Winters 31
32 data area for z data area for y data area for y data area for y data area for Main data area for Main data area for Main data area for Main Start program Enter y Enter z from y Exit z data area for Main Exit y data area for z data area for Main Enter z from Main data area for Main Exit z (c) S. Thompson, M. Winters 32
33 Activation Records An activation record is the set of local variables & parameter references, along with system information system information contains return address restore stack pointer a.k.a. dynamic chain Static chains Required in languages with nested procedures Pointer points to the data area of it s textually enclosing block static chain access is distance up chain plus offset (c) S. Thompson, M. Winters 33
34 program Main(output); var b, d : Integer; procedure z; var e, f : Integer; begin end {z}; procedure y; var g, h : Integer; procedure x; var j, k : Integer; begin end {x}; begin z; x; end {y}; begin end. z; y; (c) S. Thompson, M. Winters 34
35 data area for Main data area for Main data area for y data area for y data area for z data area for x Run-Time stack space for e and f static chain pointer dynamic chain pointer return address space for g and h static chain pointer dynamic chain pointer return address space for b and d system information space for j and k static chain pointer dynamic chain pointer return address space for g and h static chain pointer dynamic chain pointer return address space for b and d system information when z has been called from y when x has been called from y (c) S. Thompson, M. Winters 35
36 Activation Records Recursion stack-based supports recursion each invocation has its own storage multiple ARs for different invocations of same procedure int factorial(int n) { if (n > 1) return n * factorial(n 1); else return 1; }// factorial (c) S. Thompson, M. Winters 36
37 Activation Records factorial(3) 3 * factorial(2) 3 * 2 * factorial(1) 3 * 2 * 1 data area for the call factorial(1) data area for the call factorial(2) data area for the call factorial(3) data area for the main program (c) S. Thompson, M. Winters 37
38 Forward References Many languages require a declaration before use for procedures. Allows the compiler to only do a single pass What if a() calls b() and b() calls a()? (mutual recursion) Forward references tell the compiler everything it needs to know about the procedure (c) S. Thompson, M. Winters 38
39 procedure operand(var ca : Character); forward; procedure exp( var cb : Character); begin operand(cb); while cb = + do operand(cb) end {exp}; procedure operand(var ca : Character); begin read(ca); if ca = ( then begin exp(ca); if ca <> ) then writeln( missing brackets ) end else if ca <> a then writeln( missing operand ); read(ca) end {operand}; (c) S. Thompson, M. Winters 39
40 Forward References function prototypes in C & C++ void operand(char *); function specification vs function body in Ada function a(b : Integer) return Real; function a(b : Integer) return Real is begin end a; ALGOL 60, Algol 68 & Java don t require defined before use compiler must do multiple passes (c) S. Thompson, M. Winters 40
41 Subprogram as Parameters functions and procedures passed as parameters basic principle in functional languages less widely used in imperative languages specification of function parameters types of their parameters? function slope(f(y : Real) : Real; x1, x2 : Real) : Real; begin if x1 = x2 then slope := 0 else slope := (f(x2) f(x1)) / (x2 x1) end {slope}; (c) S. Thompson, M. Winters 41
42 function straight(x : Real) : Real; begin straight := 2 * x + 1 end {straight}; function tan(x : Real) : Real; begin tan := sin(x) / cos(x) end {tan}; slope(straight, 3.8, 3.83); slope(tan, 3.8, 3.85); (c) S. Thompson, M. Winters 42
43 Subprograms as Parameters Other languages move a step furthur than Pascal by allowing procedures to be types. At it s base level, what is a procedure? A memory address to branch to. So a procedure can be represented by a reference variable In C, called a function pointer. (c) S. Thompson, M. Winters 43
44 Subprogram as Parameters Modula 2 TYPE realfunc = PROCEDURE(REAL) : REAL; var fx : realfunc; fx := straight; PROCEDURE slope(f : realfunc; x1, x2 : REAL) : REAL; BEGIN IF x1 = x2 THEN RETURN 0 ELSE RETURN (f(x2) f(x1)) / (x2 x1) END END slope; (c) S. Thompson, M. Winters 44
45 C Example void printcoursecode() { printf( "COSC 2P90\n" ); } void printcoursename() { printf( O-Ol Programming\n" ); } void DisplayString( void (*displaystring)() ) { printf( "******************************\n" ); (*displaystring)(); printf( "******************************\n" ); } int main() { DisplayString( printcoursecode ); DisplayString( printcoursename ); // local variable void (*callback)() = NULL; // assignment & calling callback = printcoursecode; (*callback)(); return 0; } (c) S. Thompson, M. Winters 45
46 Subprograms as Parameters - Ada Ada uses generics instead of subprogram parameters compile-time parameters generic instantiation creates distinct functions generic with function f(y: Real) return Real; function slope(x1, x2 : Real) return Real; function slope(x1, x2 : Real) return Real is begin if x1 = x2 then return 0; else return (f(x2) f(x1)) / (x2 x1); end slope; function straight_slope is new slope(f => straight); function tan_slope is new slope(f => tan); (c) S. Thompson, M. Winters 46
47 Methods as Parameters (not in text) In pure object-oriented languages, function pointers aren t enough Can t pass a (non-static) class method as a parameter Requires an instatiated object C++ solves this with member-function pointers float (SomeClass::*my_memfunc_ptr)(int, char *); my_memfunc_ptr = &SomeClass::some_member_func; Similar to function pointers, except they require an object to call it SomeClass *x = new SomeClass; (x->*my_memfunc_ptr)(6, "Another Arbitrary Parameter"); (c) S. Thompson, M. Winters 47
48 Delegates Special type used in.net language that abstract away the function vs member function problem Your usage shouldn t care which it is Useful for event listeners, general callbacks (c) S. Thompson, M. Winters 48
49 Delegate Example public delegate void Del(string message); public static void DelegateMethod(string message) { System.Console.WriteLine(message); } public class MethodClass { public void Method1(string message) { } public void Method2(string message) { } } MethodClass obj = new MethodClass(); Del d1 = obj.method1; Del d2 = obj.method2; Del d3 = DelegateMethod; d1( A message ); (c) S. Thompson, M. Winters 49
Other Features of Procedures
Other Features of Procedures overloading multiple procedures with same name must differ in signature result type part of signature? overriding same signature may still be able to access original method
More informationReferences and pointers
References and pointers Pointers are variables whose value is a reference, i.e. an address of a store location. Early languages (Fortran, COBOL, Algol 60) had no pointers; added to Fortran 90. In Pascal,
More informationTYPES, VALUES AND DECLARATIONS
COSC 2P90 TYPES, VALUES AND DECLARATIONS (c) S. Thompson, M. Winters 1 Names, References, Values & Types data items have a value and a type type determines set of operations variables Have an identifier
More informationG 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
More informationChapter 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
More informationSubprograms. Copyright 2015 Pearson. All rights reserved. 1-1
Subprograms Introduction Fundamentals of Subprograms Design Issues for Subprograms Local Referencing Environments Parameter-Passing Methods Parameters That Are Subprograms Calling Subprograms Indirectly
More informationSubprograms. Bilkent University. CS315 Programming Languages Pinar Duygulu
1 Subprograms CS 315 Programming Languages Pinar Duygulu Bilkent University Introduction 2 Two fundamental abstraction facilities Process abstraction Emphasized from early days Data abstraction Emphasized
More informationProgramming Languages: Lecture 11
1 Programming Languages: Lecture 11 Chapter 9: Subprograms Jinwoo Kim jwkim@jjay.cuny.edu Chapter 9 Topics 2 Introduction Fundamentals of Subprograms Design Issues for Subprograms Local Referencing Environments
More informationCS 345. Functions. Vitaly Shmatikov. slide 1
CS 345 Functions Vitaly Shmatikov slide 1 Reading Assignment Mitchell, Chapter 7 C Reference Manual, Chapters 4 and 9 slide 2 Procedural Abstraction Can be overloaded (e.g., binary +) Procedure is a named
More informationOrganization of Programming Languages CS 3200/5200N. Lecture 09
Organization of Programming Languages CS 3200/5200N Razvan C. Bunescu School of Electrical Engineering and Computer Science bunescu@ohio.edu Control Flow Control flow = the flow of control, or execution
More informationDesign 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
More informationImplementing Subprograms
1 Implementing Subprograms CS 315 Programming Languages Pinar Duygulu Bilkent University CS315 Programming Languages Pinar Duygulu The General Semantics of Calls and Returns 2 The subprogram call and return
More informationNOTE: Answer ANY FOUR of the following 6 sections:
A-PDF MERGER DEMO Philadelphia University Lecturer: Dr. Nadia Y. Yousif Coordinator: Dr. Nadia Y. Yousif Internal Examiner: Dr. Raad Fadhel Examination Paper... Programming Languages Paradigms (750321)
More informationChapter 9. Subprograms
Chapter 9 Subprograms Chapter 9 Topics Introduction Fundamentals of Subprograms Design Issues for Subprograms Local Referencing Environments Parameter-Passing Methods Parameters That Are Subprograms Calling
More informationCOP4020 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
More informationChapter 9. Def: The subprogram call and return operations of a language are together called its subprogram linkage
Def: The subprogram call and return operations of a language are together called its subprogram linkage Implementing FORTRAN 77 Subprograms Call Semantics: 1. Save the execution status of the caller 2.
More informationCS1622. Semantic Analysis. The Compiler So Far. Lecture 15 Semantic Analysis. How to build symbol tables How to use them to find
CS1622 Lecture 15 Semantic Analysis CS 1622 Lecture 15 1 Semantic Analysis How to build symbol tables How to use them to find multiply-declared and undeclared variables. How to perform type checking CS
More informationPrinciples of Programming Languages
Ting Zhang Iowa State University Computer Science Department Lecture Note 16 October 26, 2010 Control Abstraction: Subroutines 1 / 26 Outline 1 Subroutines 2 Parameter Passing 3 Generic Subroutines 2 /
More informationChapter 10. Implementing Subprograms ISBN
Chapter 10 Implementing Subprograms ISBN 0-321-33025-0 Chapter 10 Topics The General Semantics of Calls and Returns Implementing Simple Subprograms Implementing Subprograms with Stack-Dynamic Local Variables
More informationCMSC 4023 Chapter 9. Fundamentals of Subprograms Introduction
9. 9.1. Introduction Two fundamental abstraction facilities Process abstraction Emphasized from early days Data abstraction Emphasized in the1980s 9.2. 9.2.1. General Subprogram Characteristics Each subprogram
More informationChapter 10 Implementing Subprograms
Chapter 10 Implementing Subprograms The General Semantics of Calls and Returns - Definition: The subprogram call and return operations of a language are together called its subprogram linkage Implementing
More informationCS 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:
More informationChapter 9. Subprograms
Chapter 9 Subprograms Chapter 9 Topics Introduction Fundamentals of Subprograms Design Issues for Subprograms Local Referencing Environments Parameter-Passing Methods Parameters That Are Subprograms Calling
More informationG 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
More informationUNIT V Sub u P b ro r g o r g a r m a s
UNIT V SubPrograms Outline Subprograms Parameter Passing Parameter correspondence Main Issues when designing subroutine in programming languages Parameter passing techniques Characteristics of Subprogram
More informationLecture 9: Parameter Passing, Generics and Polymorphism, Exceptions
Lecture 9: Parameter Passing, Generics and Polymorphism, Exceptions COMP 524 Programming Language Concepts Stephen Olivier February 12, 2008 Based on notes by A. Block, N. Fisher, F. Hernandez-Campos,
More informationIntroduction to Programming Using Java (98-388)
Introduction to Programming Using Java (98-388) Understand Java fundamentals Describe the use of main in a Java application Signature of main, why it is static; how to consume an instance of your own class;
More informationTopic 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
More informationInformatica 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
More informationTopic IV. Block-structured procedural languages Algol and Pascal. References:
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. Chapters 10( 2) and 11( 1) of Programming
More informationG Programming Languages - Fall 2012
G22.2110-003 Programming Languages - Fall 2012 Lecture 3 Thomas Wies New York University Review Last week Names and Bindings Lifetimes and Allocation Garbage Collection Scope Outline Control Flow Sequencing
More informationProgramming Languages: Lecture 12
1 Programming Languages: Lecture 12 Chapter 10: Implementing Subprograms Jinwoo Kim jwkim@jjay.cuny.edu Chapter 10 Topics 2 The General Semantics of Calls and Returns Implementing Simple Subprograms Implementing
More informationReview of the C Programming Language
Review of the C Programming Language Prof. James L. Frankel Harvard University Version of 11:55 AM 22-Apr-2018 Copyright 2018, 2016, 2015 James L. Frankel. All rights reserved. Reference Manual for the
More informationAttributes, 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
More informationCS 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
More informationNames, Scopes, and Bindings II. Hwansoo Han
Names, Scopes, and Bindings II Hwansoo Han Scope Rules A scope is textual region where bindings are active A program section of maximal size Bindings become active at the entry No bindings change in the
More informationSEMANTIC ANALYSIS TYPES AND DECLARATIONS
SEMANTIC ANALYSIS CS 403: Type Checking Stefan D. Bruda Winter 2015 Parsing only verifies that the program consists of tokens arranged in a syntactically valid combination now we move to check whether
More informationLexical Considerations
Massachusetts Institute of Technology Department of Electrical Engineering and Computer Science 6.035, Fall 2005 Handout 6 Decaf Language Wednesday, September 7 The project for the course is to write a
More information1 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
More informationObject-oriented programming. and data-structures CS/ENGRD 2110 SUMMER 2018
Object-oriented programming 1 and data-structures CS/ENGRD 2110 SUMMER 2018 Lecture 1: Types and Control Flow http://courses.cs.cornell.edu/cs2110/2018su Lecture 1 Outline 2 Languages Overview Imperative
More informationChapter 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
More informationChapter 10. Implementing Subprograms
Chapter 10 Implementing Subprograms Chapter 10 Topics The General Semantics of Calls and Returns Implementing Simple Subprograms Implementing Subprograms with Stack-Dynamic Local Variables Nested Subprograms
More informationRun-Time Data Structures
Run-Time Data Structures Static Structures For static structures, a fixed address is used throughout execution. This is the oldest and simplest memory organization. In current compilers, it is used for:
More informationChapter 8. Fundamental Characteristics of Subprograms. 1. A subprogram has a single entry point
Fundamental Characteristics of Subprograms 1. A subprogram has a single entry point 2. The caller is suspended during execution of the called subprogram 3. Control always returns to the caller when the
More informationLecture 11: Subprograms & their implementation. Subprograms. Parameters
Lecture 11: Subprograms & their implementation Subprograms Parameter passing Activation records The run-time stack Implementation of static and dynamic scope rules Subprograms A subprogram is a piece of
More informationCS558 Programming Languages Winter 2018 Lecture 4a. Andrew Tolmach Portland State University
CS558 Programming Languages Winter 2018 Lecture 4a Andrew Tolmach Portland State University 1994-2018 Pragmatics of Large Values Real machines are very efficient at handling word-size chunks of data (e.g.
More informationSE352b: Roadmap. SE352b Software Engineering Design Tools. W3: Programming Paradigms
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
More informationCSE 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
More information9. Subprograms. 9.2 Fundamentals of Subprograms
9. Subprograms 9.2 Fundamentals of Subprograms General characteristics of subprograms A subprogram has a single entry point The caller is suspended during execution of the called subprogram Control always
More informationInstantiation of Template class
Class Templates Templates are like advanced macros. They are useful for building new classes that depend on already existing user defined classes or built-in types. Example: stack of int or stack of double
More informationShort 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
More informationPass by Value. Pass by Value. Our programs are littered with function calls like f (x, 5).
Our programs are littered with function calls like f (x, 5). This is a way of passing information from the call site (where the code f(x,5) appears) to the function itself. The parameter passing mode tells
More informationSubroutines. Subroutine. Subroutine design. Control abstraction. If a subroutine does not fit on the screen, it is too long
Subroutines Subroutine = procedure (statement) - no return value - side effects function (expression) - return value - (no side effects in some languages) Subroutine Control abstraction Subroutine design
More informationCS201 - Introduction to Programming Glossary By
CS201 - Introduction to Programming Glossary By #include : The #include directive instructs the preprocessor to read and include a file into a source code file. The file name is typically enclosed with
More informationRuby: Introduction, Basics
Ruby: Introduction, Basics Computer Science and Engineering College of Engineering The Ohio State University Lecture 3 Ruby vs Java: Similarities Imperative and object-oriented Classes and instances (ie
More informationImplementing Subprograms
Implementing Subprograms 1 Topics The General Semantics of Calls and Returns Implementing Simple Subprograms Implementing Subprograms with Stack-Dynamic Local Variables Nested Subprograms Blocks Implementing
More informationknown as non-void functions/methods in C/C++/Java called from within an expression.
FUNCTIONS 1 OUTLINE Basic Terminology Function Call and Return Parameters Parameter Passing Mechanisms Activation Records Recursive Functions Run Time Stack Function Declaration and Call in Clite Completing
More informationCSC 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
More informationCS558 Programming Languages
CS558 Programming Languages Winter 2017 Lecture 4a Andrew Tolmach Portland State University 1994-2017 Semantics and Erroneous Programs Important part of language specification is distinguishing valid from
More informationLexical 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
More informationCompilers. 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:
More informationFundamental Concepts and Definitions
Fundamental Concepts and Definitions Identifier / Symbol / Name These terms are synonymous: they refer to the name given to a programming component. Classes, variables, functions, and methods are the most
More informationCS558 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.
More informationLECTURE 18. Control Flow
LECTURE 18 Control Flow CONTROL FLOW Sequencing: the execution of statements and evaluation of expressions is usually in the order in which they appear in a program text. Selection (or alternation): a
More informationProperties 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
More informationImperative Languages!
Imperative Languages! Java is an imperative object-oriented language. What is the difference in the organisation of a program in a procedural and an objectoriented language? 30 class BankAccount { private
More informationLecture 5: Methods CS2301
Lecture 5: Methods NADA ALZAHRANI CS2301 1 Opening Problem Find the sum of integers from 1 to 10, from 20 to 30, and from 35 to 45, respectively. 2 Solution public static int sum(int i1, int i2) { int
More informationProgramming 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
More informationCS 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
More informationG 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
More informationOBJECT ORIENTED PROGRAMMING USING C++ CSCI Object Oriented Analysis and Design By Manali Torpe
OBJECT ORIENTED PROGRAMMING USING C++ CSCI 5448- Object Oriented Analysis and Design By Manali Torpe Fundamentals of OOP Class Object Encapsulation Abstraction Inheritance Polymorphism Reusability C++
More informationFunctions and Recursion
Programming Languages Functions and Recursion Dr. Philip Cannata 1 10 High Level Languages This Course Jython in Java Java (Object Oriented) ACL2 (Propositional Induction) Relation Algorithmic Information
More informationQUIZ. 1. Explain the meaning of the angle brackets in the declaration of v below:
QUIZ 1. Explain the meaning of the angle brackets in the declaration of v below: This is a template, used for generic programming! QUIZ 2. Why is the vector class called a container? 3. Explain how the
More informationCompiler Construction
Compiler Construction Thomas Noll Software Modeling and Verification Group RWTH Aachen University https://moves.rwth-aachen.de/teaching/ss-17/cc/ Generation of Intermediate Code Conceptual Structure of
More informationSpecial Topics: Programming Languages
Lecture #17 0 V22.0490.001 Special Topics: Programming Languages B. Mishra New York University. Lecture # 17 Lecture #17 1 Slide 1 Runtime Representations Variable Names Environment L-values Scope, Extent
More informationPaytm Programming Sample paper: 1) A copy constructor is called. a. when an object is returned by value
Paytm Programming Sample paper: 1) A copy constructor is called a. when an object is returned by value b. when an object is passed by value as an argument c. when compiler generates a temporary object
More informationChapter 6 Introduction to Defining Classes
Introduction to Defining Classes Fundamentals of Java: AP Computer Science Essentials, 4th Edition 1 Objectives Design and implement a simple class from user requirements. Organize a program in terms of
More informationCompiler Construction
Compiler Construction Thomas Noll Software Modeling and Verification Group RWTH Aachen University https://moves.rwth-aachen.de/teaching/ss-17/cc/ Generation of Intermediate Code Outline of Lecture 15 Generation
More informationChapter 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?
More informationWeeks 6&7: Procedures and Parameter Passing
CS320 Principles of Programming Languages Weeks 6&7: Procedures and Parameter Passing Jingke Li Portland State University Fall 2017 PSU CS320 Fall 17 Weeks 6&7: Procedures and Parameter Passing 1 / 45
More informationIntroduction to Programming (Java) 4/12
Introduction to Programming (Java) 4/12 Michal Krátký Department of Computer Science Technical University of Ostrava Introduction to Programming (Java) 2008/2009 c 2006 2008 Michal Krátký Introduction
More informationCS558 Programming Languages
CS558 Programming Languages Fall 2016 Lecture 4a Andrew Tolmach Portland State University 1994-2016 Pragmatics of Large Values Real machines are very efficient at handling word-size chunks of data (e.g.
More information6. Names, Scopes, and Bindings
Copyright (C) R.A. van Engelen, FSU Department of Computer Science, 2000-2004 6. Names, Scopes, and Bindings Overview Names Binding time Object lifetime Object storage management Static allocation Stack
More information1 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
More informationCSE 374 Programming Concepts & Tools
CSE 374 Programming Concepts & Tools Hal Perkins Fall 2017 Lecture 8 C: Miscellanea Control, Declarations, Preprocessor, printf/scanf 1 The story so far The low-level execution model of a process (one
More information9/21/17. Outline. Expression Evaluation and Control Flow. Arithmetic Expressions. Operators. Operators. Notation & Placement
Outline Expression Evaluation and Control Flow In Text: Chapter 6 Notation Operator evaluation order Operand evaluation order Overloaded operators Type conversions Short-circuit evaluation of conditions
More information22c:111 Programming Language Concepts. Fall Types I
22c:111 Programming Language Concepts Fall 2008 Types I Copyright 2007-08, The McGraw-Hill Company and Cesare Tinelli. These notes were originally developed by Allen Tucker, Robert Noonan and modified
More informationType Checking Binary Operators
Type Checking Binary Operators binaryopnode expr tree expr tree Type checking steps: 1. Type check left and right operands. 2. Check that left and right operands are both scalars. 3. binaryopnode.kind
More informationProgramming Languages & Paradigms PROP HT Course Council. Subprograms. Meeting on friday! Subprograms, abstractions, encapsulation, ADT
Programming Languages & Paradigms PROP HT 2011 Lecture 4 Subprograms, abstractions, encapsulation, ADT Beatrice Åkerblom beatrice@dsv.su.se Course Council Meeting on friday! Talk to them and tell them
More informationCompiler Design. Spring Run-Time Environments. Sample Exercises and Solutions. Prof. Pedro C. Diniz
University of Southern California (USC) Computer Science Department Compiler Design Spring 2014 Run-Time Environments Sample Exercises and Solutions Prof. Pedro C. Diniz USC / Information Sciences Institute
More informationCSc 520 Principles of Programming Languages. 26 : Control Structures Introduction
CSc 520 Principles of Programming Languages 26 : Control Structures Introduction Christian Collberg Department of Computer Science University of Arizona collberg+520@gmail.com Copyright c 2008 Christian
More informationName :. Roll No. :... Invigilator s Signature : INTRODUCTION TO PROGRAMMING. Time Allotted : 3 Hours Full Marks : 70
Name :. Roll No. :..... Invigilator s Signature :.. 2011 INTRODUCTION TO PROGRAMMING Time Allotted : 3 Hours Full Marks : 70 The figures in the margin indicate full marks. Candidates are required to give
More informationChapter 8 ( ) Control Abstraction. Subprograms Issues related to subprograms How is control transferred to & from the subprogram?
Control Abstraction Chapter 8 (81 84) Control Abstraction: Subroutines and parameters Programmer defined control structures Subprograms Procedures Functions Coroutines Exception handlers Processes Subprograms
More informationBinding 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
More informationCOMP 250: Java Programming I. Carlos G. Oliver, Jérôme Waldispühl January 17-18, 2018 Slides adapted from M. Blanchette
COMP 250: Java Programming I Carlos G. Oliver, Jérôme Waldispühl January 17-18, 2018 Slides adapted from M. Blanchette Variables and types [Downey Ch 2] Variable: temporary storage location in memory.
More informationSemantic Analysis and Type Checking
Semantic Analysis and Type Checking The compilation process is driven by the syntactic structure of the program as discovered by the parser Semantic routines: interpret meaning of the program based on
More informationChapter 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
More informationAn Activation Record for Simple Subprograms. Activation Record for a Language with Stack-Dynamic Local Variables
Activation Records The storage (for formals, local variables, function results etc.) needed for execution of a subprogram is organized as an activation record. An Activation Record for Simple Subprograms.
More informationChapter 1 Getting Started
Chapter 1 Getting Started The C# class Just like all object oriented programming languages, C# supports the concept of a class. A class is a little like a data structure in that it aggregates different
More informationCOSC 2P95. Procedural Abstraction. Week 3. Brock University. Brock University (Week 3) Procedural Abstraction 1 / 26
COSC 2P95 Procedural Abstraction Week 3 Brock University Brock University (Week 3) Procedural Abstraction 1 / 26 Procedural Abstraction We ve already discussed how to arrange complex sets of actions (e.g.
More information