Imperative Programming. Heart of program is assignment statements Aware that memory contains instructions and data values Commands: variable declarations,

Slides:



Advertisements
Similar presentations
Lectures 10 & 11.
Advertisements

Programming Languages and Paradigms
What is a pointer? First of all, it is a variable, just like other variables you studied So it has type, storage etc. Difference: it can only store the.
Parameter Passing. Variables: lvalues and rvalues In the assignment statement “X=Y”, variables X and Y are being used in different ways. Y is being used.
PZ09B Programming Language design and Implementation -4th Edition Copyright©Prentice Hall, PZ09B - Parameter transmission Programming Language Design.
Slide 1 Vitaly Shmatikov CS 345 Functions. slide 2 Reading Assignment uMitchell, Chapter 7 uC Reference Manual, Chapters 4 and 9.
PZ09B Programming Language design and Implementation -4th Edition Copyright©Prentice Hall, PZ09B - Parameter transmission Programming Language Design.
Subprograms A subprogram allows process abstraction (as opposed to data abstraction). Characteristics –single entry point –caller suspended until control.
CPSC 388 – Compiler Design and Construction Parameter Passing.
CSCI 330: Programming Language Concepts Instructor: Pranava K. Jha
Procedures and Control Flow CS351 – Programming Paradigms.
Lecture 16 Subroutine Calls and Parameter Passing Semantics Dragon: Sec. 7.5 Fischer: Sec Procedure declaration procedure p( a, b : integer, f :
Principles of programming languages 4: Parameter passing, Scope rules Department of Information Science and Engineering Isao Sasano.
1 Pointers A pointer variable holds an address We may add or subtract an integer to get a different address. Adding an integer k to a pointer p with base.
Chapter 9 Subprogram Control Consider program as a tree- –Each parent calls (transfers control to) child –Parent resumes when child completes –Copy rule.
Chapter 9 Subprograms Sections 1-5 and 9. Copyright © 2007 Addison-Wesley. All rights reserved. 1–2 Introduction Two fundamental abstraction facilities.
1 1 Lecture 4 Structure – Array, Records and Alignment Memory- How to allocate memory to speed up operation Structure – Array, Records and Alignment Memory-
CSSE221: Software Dev. Honors Day 27 Announcements Announcements Projects turned in? Projects turned in? The 2 required Angel surveys are due by 9 pm tonight.
PSUCS322 HM 1 Languages and Compiler Design II Parameter Passing Material provided by Prof. Jingke Li Stolen with pride and modified by Herb Mayer PSU.
CS 61C L4 Structs (1) A Carle, Summer 2005 © UCB inst.eecs.berkeley.edu/~cs61c/su05 CS61C : Machine Structures Lecture #4: Strings & Structs
ARRAYS AND POINTERS Although pointer types are not integer types, some integer arithmetic operators can be applied to pointers. The affect of this arithmetic.
Review on pointers and dynamic objects. Memory Management  Static Memory Allocation  Memory is allocated at compiling time  Dynamic Memory  Memory.
Parameter Passing. Expressions with lvalues and rvalues An expression has an lvalue/rvalue if it can be placed on the left/right side of an assignment.
Overview Parameter passing modes.
1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation –The new operator –The delete operator –Dynamic.
CSC321: Programming Languages1 Programming Languages Tucker and Noonan Chapter 9: Functions 9.1 Basic Terminology 9.2 Function Call and Return 9.3 Parameters.
Copyright © 2006 The McGraw-Hill Companies, Inc. Programming Languages 2nd edition Tucker and Noonan Chapter 9 Functions It is better to have 100 functions.
1 Procedural Concept The main program coordinates calls to procedures and hands over appropriate data as parameters.
Pointers CSE 2451 Rong Shi.
© 2003 G. Drew Kessler and William M. Pottenger1 Subroutines (Part 1) CSE 262, Spring 2003.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 19 Clicker Questions November 3, 2009.
18-2 Understand “Scope” of an Identifier Know the Storage Classes of variables and functions Related Chapter: ABC 5.10, 5.11.
CS 2104 Prog. Lang. Concepts Subprograms
CS50 SECTION: WEEK 4 Kenny Yu. Announcements  Problem Set 4 Walkthrough online  Problem Set 2 Feedback has been sent out  CORRECTION: Expect all future.
Programming Languages and Design Lecture 7 Subroutines and Control Abstraction Instructor: Li Ma Department of Computer Science Texas Southern University,
Chapter 9 Functions It is better to have 100 functions operate on one data structure than 10 functions on 10 data structures. A. Perlis.
Copyright © 2005 Elsevier Chapter 8 :: Subroutines and Control Abstraction Programming Language Pragmatics Michael L. Scott.
Dr. Philip Cannata 1 Functions and Recursion. Dr. Philip Cannata 2 10 Java (Object Oriented) ASP RDF (Horn Clause Deduction, Semantic Web) Relation Jython.
Programming Languages and Paradigms Imperative Programming.
Copyright 2005, The Ohio State University 1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation.
19&20-2 Know how to declare pointer variables. Understand the & (address) and *(indirection) operators. Dynamic Memory Allocation Related Chapter: ABC.
Topic 3: C Basics CSE 30: Computer Organization and Systems Programming Winter 2011 Prof. Ryan Kastner Dept. of Computer Science and Engineering University.
Copyright © 2006 The McGraw-Hill Companies, Inc. Basic Terminology Value-returning functions: –known as “non-void functions/methods” in C/C++/Java –called.
Slide 1 Dr. Mohammad El-Ramly Fall 2010 Set 7- II - Functions Slides by Vitaly Shmatikov Cairo University Faculty of Computers and Information CS317 Concepts.
Structure of Programming Languages Names, Bindings, Type Checking, and Scopes.
C Programming - Structures. Structures containing arrays A structure member that is an array does not ‘behave’ like an ordinary array When copying a structure.
Computer Organization and Design Pointers, Arrays and Strings in C Montek Singh Sep 18, 2015 Lab 5 supplement.
How to execute Program structure Variables name, keywords, binding, scope, lifetime Data types – type system – primitives, strings, arrays, hashes – pointers/references.
CSE 3302 Programming Languages
CMPSC 16 Problem Solving with Computers I Spring 2014 Instructor: Lucas Bang Lecture 11: Pointers.
Dr. Philip Cannata 1 Functions and Recursion Programming Languages.
1 CSC 533: Programming Languages Spring 2014 Subprogram implementation  subprograms (procedures/functions/subroutines)  subprogram linkage  parameter.
C Tutorial - Pointers CS 537 – Introduction to Operating Systems.
Imperative Programming C. Imperative Programming Heart of program is assignment statements Aware that memory contains instructions and data values Commands:
CS314 – Section 5 Recitation 9
Computer Organization and Design Pointers, Arrays and Strings in C
Functions.
Principles of programming languages 4: Parameter passing, Scope rules
C Basics.
Lecture 6 C++ Programming
Object Oriented Programming COP3330 / CGS5409
Pointers, Dynamic Data, and Reference Types
CSC 533: Programming Languages Spring 2015
CSE 3302 Programming Languages
Parameter transmission
PZ09B - Parameter transmission
Parameter transmission
CSC 533: Programming Languages Spring 2018
CSC 533: Programming Languages Spring 2019
Parameter transmission
Presentation transcript:

Imperative Programming

Heart of program is assignment statements Aware that memory contains instructions and data values Commands: variable declarations, loops, conditionals, procedural abstraction Commands make a flowchart

Imperative Languages FORTRAN COBOL BASIC Pascal C

Pascal Example program Loops; var i: Integer; begin for i := 1 to 10 do begin Writeln('Hello'); Writeln('This is loop ',i); end; end.

C Example /*Hello, world” */ #include main() { printf(“Howdy, earth! \n”); return 0; }

C Printing Print strings directly Other types must be converted, because they are really numbers: char c = ‘A’; printf(“Print char c: %c.\n”,c); int n = 6; printf(“Print int n: %d.\n”,n);

Increment/Decrement (P.S. Same in Java) int x,y,z; x=y=z=1; y = x++; x=1; z = ++x; printf("x++ gives %d\n",y); printf("++x gives %d\n",z);

C-isms 0 is false, 1 is true (or non-zero) Same logical operators, &&, ||, ! But there are also bitwise operators &, |, ~ Other bitwise operators: ^, >>, << x ? y : z means “if x, y, else z” (Same as Java) char c = x > 0? ‘T’ : ‘F’

Memory Addresses (C) Pointers are addresses of where values are stored in memory. &variable means “address of variable” What happens? int a = 13; printf("a is %d\n",a); printf("&a is %p\n",&a);

Pointers in C int* ptr; -> ptr is a pointer to an int (with no pointee!) What does it do? int *ptr; int num = 4; ptr = &num;

More Pointer Fun in C int *ptr; int num = 4; ptr = &num; *ptr = 5;

Pointers in Pascal program Pointers; var p: ^integer; begin new(p); p^ := 3; writeln(p^); dispose(p); end.

C Arrays int arInt[5]; int arInt2[5] = {1,4,3,2,1}; int ar[2][3] = {{1,2,3},{4,5,6}};

C Strings char str[] = “I like C.”; char *ptrStr = “I love pointers.”; Last character in String is ‘\0’

C Strings – Example: Compute length of string int myStrLen(const char* s) { int count = 0; while (*s != ‘\0’) { count++; s++; } return count; }

Preprocessor Directives #define – substitute before compiling: #define MAX 1000 if(x > MAX)…

C Scope Modifiers static: don’t delete from memory - permanent duration register: suggest use of register for variable. Can’t ask for address of the variable const: make a variable constant. When pointers are const, their “pointees” are constant

Memory malloc: allocates memory. Must give number of bytes wanted. malloc function returns a pointer to the memory. (Null ptr if memory error). free: frees memory. char *ptr; char str[] = “String!”; ptr = malloc(strlen(str) + 1); free(ptr);

Defining new types Struct (record in other langs) typedef struct{ char* word; int frequency; int size; } wordInfo; wordInfo wordOne; wordOne.word = “apple”; wordOne.frequency = 0; wordOne.size = 0;

Pointers to Structs We often use pointers to structs (do you know why? wordInfo *wiPtr; Can dereference explicitly: wordInfo wi = *wiPtr; Or shortcut straight to the fields: int f = wiPtr->frequency;

What C Lacks Iterators Exception Handling Overloading Generics

Parameter Passing Pass by value vs Pass by reference What’s it like in Java?

Parameter Passing Mechanisms By value By reference By value-result By name

Pass by Value Compute the value of the argument at the time of the call and assign that value to the parameter. So passing by value doesn’t normally allow the called function to modify an argument’s value. All arguments in C and Java are passed by value. But references can be passed to allow argument values to be modified. E.g., void swap(int *a, int *b) { … }

A Look at Swapping - Java 1 void swap(int a, int b){ int t = a; a = b; b = a; } int x = 3; int y = 4; swap(x,y); System.out.println("x value: "+x+" y value: "+y);

A Look at Swapping - Java 2 void swap2(int[] array, int a, int b){ int t = array[a]; array[a] = array[b]; array[b] = t; } int[] arr = {0,1}; swap2(arr, 0,1); System.out.println("array: "+arr[0]+” "+arr[1]);

A Look at Swapping - Java 3 void swap3(Double a, Double b){ Double t = a; a = b; b = t; } Double a = new Double(3.0); Double b = new Double(4.0); swap3(a,b); System.out.println("a value: "+a.doubleValue()+" b value: "+b.doubleValue());

A Look at Swapping - C1 void swap(int a, int b){ int t = a; a = b; b = t; } int main(void){ int a = 3; int b = 4; swap(a,b); printf("a value is %d and b value is %d", a, b); return 0; }

A Look at Swapping - C2 void swap2(int* a, int* b){ int temp = *a; *a = *b; *b = temp; } int main(void){ int a = 3; int b = 4; swap2(&a,&b); printf("a value is %d and b value is %d", a, b); return 0; }

C++ Swapping - Pass by Reference/Value int main(void){ int a = 3; int b = 4; swap(a,b); printf("a value is %d and b value is %d", a, b); return 0; } void swap(int a, int b){ int temp = a; a = b; b = temp; } void swap(int& a, int& b){ int temp = a; a = b; b = temp; }

Pass by Reference Compute the address of the argument at the time of the call and assign it to the parameter. Example Since h is passed by reference, its value changes during the call to B. int h, i; void B(int* w) { int j, k; i = 2*(*w); *w = *w+1; } void A(int* x, int* y) { bool i, j; B(&h); } int main() { int a, b; h = 5; a = 3; b = 2; A(&a, &b); }

Pass by Value-Result Pass by value at the time of the call and copy the result back to the argument at the end of the call. – E.g., Ada’s in out parameter can be implemented as value-result. – Value-result is often called copy-in-copy-out. Reference and value-result are the same, except when aliasing occurs.

Aliasing 2 Names for same thing: Java example: Object o = new Object… Object x = o; Can happen other ways as well: Pass variable as parameter and refer to it globally Pass variable by reference twice

When Pass-by-Value-Result gives different answers… (Ada:) procedure f (x,y: in out Integer) is begin x := x + 1; y := y + 1; end f; f(a,a) increments a by ONE only.

More on Pass by Value-Result -Sometimes the order of copying makes a difference! Different with different implementations of language. Ex: f(i,a[i]) -> change i first or a[i] first? -All actual parameters must be l-values - things that can be assigned. (Same in pass- by-reference!) Ex: f(a+1) -> How would it be copied back in?

Pass by Name Textually substitute the argument for every instance of its corresponding parameter in the function body. – Originated with Algol 60 (Jensen’s device), but was dropped by Algol’s successors -- Pascal, Ada, Modula. – Exemplifies late binding, since evaluation of the argument is delayed until its occurrence in the function body is actually executed. – Associated with lazy evaluation in functional languages

When Pass by Name Gives different results Algol 60: procedure swap(a,b); integer a,b; begin integer t; t := a; a := b; b:= t end; Call swap(i, a[i]). Method becomes: begin integer t; t := i; i := a[i]; a[i]:= t end; i = 0, a=[3,0,0,0]. Want: i=3, a = [0,0,0,0]. What really happens? What happens if I call swap(a[i],i) instead?