CS 103 Unit 13 Slides

Similar documents
CSCI 104 Memory Allocation. Mark Redekopp David Kempe

Agenda. The main body and cout. Fundamental data types. Declarations and definitions. Control structures

CS 103 Unit 12 Slides

Arrays in C++ Instructor: Andy Abreu

C++ for Java Programmers

Pointers, Dynamic Data, and Reference Types

EE 355 Unit 10. C++ STL - Vectors and Deques. Mark Redekopp

CS 103 Unit 15. Doubly-Linked Lists and Deques. Mark Redekopp

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

! Pass by value: when an argument is passed to a. ! It is implemented using variable initialization. ! Changes to the parameter in the function body

Lab 2: Pointers. //declare a pointer variable ptr1 pointing to x. //change the value of x to 10 through ptr1

FORM 1 (Please put your name and section number (001/10am or 002/2pm) on the scantron!!!!) CS 161 Exam II: True (A)/False(B) (2 pts each):

REFERENCES, POINTERS AND STRUCTS

pointers + memory double x; string a; int x; main overhead int y; main overhead

Goals of this Lecture

BITG 1113: POINTER LECTURE 12

Pointers and Arrays CS 201. This slide set covers pointers and arrays in C++. You should read Chapter 8 from your Deitel & Deitel book.

CS 103 Unit 11. Linked Lists. Mark Redekopp

CS 103 Unit 11. Linked Lists. Mark Redekopp

Pointers, Arrays and C-Strings

Week 3: Pointers (Part 2)

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

Exercise 1.1 Hello world

Midterm Exam #2 Spring (1:00-3:00pm, Friday, March 15)

[CSE10200] Programming Basis ( 프로그래밍기초 ) Chapter 9. Seungkyu Lee. Assistant Professor, Dept. of Computer Engineering Kyung Hee University

Introducing C++ to Java Programmers

CS103 Unit 6 - Pointers. Mark Redekopp

CS103 Unit 6 - Pointers. Mark Redekopp

EE 355 Unit 11b. Doubly-Linked Lists and Deques. Mark Redekopp

Object Reference and Memory Allocation. Questions:

Homework #3 CS2255 Fall 2012

C++ For Science and Engineering Lecture 15

Exam 3 Chapters 7 & 9

Functions, Arrays & Structs

Name MULTIPLE CHOICE. Choose the one alternative that best completes the statement or answers the question.

THE GOOD, BAD AND UGLY ABOUT POINTERS. Problem Solving with Computers-I

CS24 Week 3 Lecture 1

Lab Instructor : Jean Lai

CS 103 Unit 14. Classes Revisited. Mark Redekopp

Pointers and Strings Chapters 10, Pointers and Arrays (10.3) 3.2 Pointers and Arrays (10.3) An array of ints can be declared as

Lecture 23: Pointer Arithmetic

Introduction to C++ Professor Hugh C. Lauer CS-2303, System Programming Concepts

CS2255 HOMEWORK #1 Fall 2012

Lecture on pointers, references, and arrays and vectors

Constants, References

CS 103 Lab - Party Like A Char Star

6. Pointers, Structs, and Arrays. March 14 & 15, 2011

University of Illinois at Urbana-Champaign Department of Computer Science. First Examination

l Determine if a number is odd or even l Determine if a number/character is in a range - 1 to 10 (inclusive) - between a and z (inclusive)

Topics. Functions. Functions

1. Which of the following best describes the situation after Line 1 has been executed?

Computer Programming

CSE 374 Programming Concepts & Tools. Hal Perkins Spring 2010

Pointers. Pointer Variables. Chapter 11. Pointer Variables. Pointer Variables. Pointer Variables. Declaring Pointer Variables

First Examination. CS 225 Data Structures and Software Principles Spring p-9p, Tuesday, February 19

CS 31 Discussion 1A, Week 4. Zengwen Yuan (zyuan [at] cs.ucla.edu) Humanities A65, Friday 10:00 11:50 a.m.

BITG 1113: Function (Part 2) LECTURE 5

CA31-1K DIS. Pointers. TA: You Lu

6. Pointers, Structs, and Arrays. 1. Juli 2011

Discussion 1E. Jie(Jay) Wang Week 10 Dec.2

! Determine if a number is odd or even. ! Determine if a number/character is in a range. - 1 to 10 (inclusive) - between a and z (inclusive)

3/22/2016. Pointer Basics. What is a pointer? C Language III. CMSC 313 Sections 01, 02. pointer = memory address + type

CS 240 Data Structure Spring 2018 Exam I 03/01/2018

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

Review Questions for Final Exam

10/20/2015. Midterm Topic Review. Pointer Basics. C Language III. CMSC 313 Sections 01, 02. Adapted from Richard Chang, CMSC 313 Spring 2013

Patterns: Working with Arrays

Learning Recursion. Recursion [ Why is it important?] ~7 easy marks in Exam Paper. Step 1. Understand Code. Step 2. Understand Execution

Week 3. Function Definitions. Example: Function. Function Call, Return Statement. Functions & Arrays. Gaddis: Chapters 6 and 7.

EE 355 Lab 4 - Party Like A Char Star

CS 103 Lab 6 - Party Like A Char Star

Chapter 1: Object-Oriented Programming Using C++

Pointers. Variable Declaration. Chapter 10


Chapter 6: User-Defined Functions. Objectives (cont d.) Objectives. Introduction. Predefined Functions 12/2/2016

Lesson 13 - Vectors Dynamic Data Storage

Basic memory model Using functions Writing functions. Basics Prototypes Parameters Return types Functions and memory Names and namespaces

Intermediate Programming, Spring 2017*

CS102 Software Engineering Principles

04-19 Discussion Notes

! Determine if a number is odd or even. ! Determine if a number/character is in a range. ! Assign a category based on ranges (wind speed)

2 is type double 3 auto i = 1 + 2; // evaluates to an 4 integer, so it is int. 1 auto d = 5.0; // 5.0 is a double literal, so it

Pointers and Strings. Adhi Harmoko S, M.Komp

C++ Primer for CS175

CISC220 Lab 2: Due Wed, Sep 26 at Midnight (110 pts)

What we will learn about this week: Declaring and referencing arrays. arrays as function arguments. Arrays

FORM 2 (Please put your name and form # on the scantron!!!!)

THE STANDARD TEMPLATE LIBRARY (STL) Week 6 BITE 1513 Computer Game Programming

Consider the above code. This code compiles and runs, but has an error. Can you tell what the error is?

EECS402 Lecture 02. Functions. Function Prototype

CMSC202 Computer Science II for Majors

CS93SI Handout 04 Spring 2006 Apr Review Answers

CS Introduction to Programming Midterm Exam #2 - Prof. Reed Fall 2015

Intermediate Programming & Design (C++) Classes in C++

Jordan University of Science & Technology Department of Computer Science CS 211 Exam #1 (23/10/2010) -- Form A

University of Illinois at Urbana-Champaign Department of Computer Science. First Examination

Chapter 9: Pointers Co C pyr py igh i t gh Pear ea so s n n E ducat ca io i n, n Inc. n c.

Midterm Practice Exam

Exercises with Linked Lists CS 16: Solving Problems with Computers I Lecture #15

PIC 10A. Final Review: Part I

Transcription:

1 CS 103 Unit 13 Slides C++ References Mark Redekopp

2 Swap Two Variables Classic example of issues with local variables: Write a function to swap two variables Pass-b-value doesn t work Cop is made of x, from main and passed to x, of swapit Swap is performed on the copies Pass-b-reference (pointers) does work Addresses of the actual x, variables in main are passed Use those address to change those phsical memor locations int x=5,=7; swapit(x,); cout << x,= << x <<, << << endl; void swapit(int x, int ) int temp; temp = x; x = ; = temp; program output: x=5,=7 int x=5,=7; swapit(&x,&); cout << x,= << x <<, << << endl; void swapit(int *x, int *) int temp; temp = *x; *x = *; * = temp; program output: x=7,=5

3 C++ Reference Variables So ou want a function to actuall modif a variable from another function but ou don t like pointers and the confuse ou? Too bad. Don t give up! You CAN understand pointers keep working at it BUT You can also use C++ Reference variables C++ reference variables essentiall pass arguments via pointer/address but use the sntax of pass-bvalue (i.e. no more de-referencing)

4 Using C++ Reference Variables To declare a reference variable, use the & operator in a declaration! Poor choice b C++ because it is confusing since & is alread used for the address of operator when used in an expression (i.e. non-declaration) Behind the scenes the compiler will essentiall access variable with a pointer But ou get to access it like a normal variable without dereferencing Think of a reference variable as an alias With Pointers 0x1a0 3 0x1a0 3 x 0x1a0 With References - Phsicall x 0x1a0 With References - Logicall 3 x int = 3; doit(&); //address-of oper. cout << << endl; int doit(int *x) *x = *x - 1; return *x; Using pointers int = 3; doit(); cout << << endl; int doit(int &x) // Ref. dec. x = x - 1; return x; Using C++ References Output: 2 in both programs

5 Swap Two Variables Pass-b-value => Passes a cop Pass-b-reference => Pass-b-pointer/address => Passes address of actual variable Pass-b-reference => Passes an alias to actual variable int x=5,=7; swapit(x,); cout << x,= << x<<, << ; cout << endl; void swapit(int x, int ) int temp; temp = x; x = ; = temp; program output: x=5,=7 int x=5,=7; swapit(&x,&); cout << x,= << x<<, << ; cout << endl; void swapit(int *x, int *) int temp; temp = *x; *x = *; * = temp; program output: x=7,=5 int x=5,=7; swapit(x,); cout << x,= << x<<, << ; cout << endl; void swapit(int &x, int &) int temp; temp = x; x = ; = temp; program output: x=7,=5

6 When to Use References Whenever ou want to actuall modif an input parameter/argument (i.e. a local variable from another function) Great for passing big struct or class objects Because no cop will be made, (pass-b-value would have wasted time coping contents to new memor) class GradeBook public: int grades[8][100]; ; GradeBook gb;... double average = process_it(gb); double process_it(gradebook& mgb) double sum = 0; for(int i=0; i < 8; i++) for(int j=0; j < 100; j++) sum += mgb.grades[i][j]; mgb.grades[0][0] = 91; sum /= (8*100); return sum;

7 Const arguments An aside: If we want an extra safet precaution for our own mistakes, we can declare arguments as 'const' The compiler will produce an error to tell ou that ou have written code that will modif the object ou said should be constant Doesn t protect against backdoors like pointers that somehow point at these data objects. class GradeBook public: int grades[8][100]; ; GradeBook gb;... double average = process_it(gb); double process_it(const GradeBook &mgb) double sum = 0; for(int i=0; i < 8; i++) for(int j=0; j < 100; j++) sum += mgb.grades[i][j]; mgb.grades[0][0] = 91; // modification of mgb // compiler will produce ERROR! sum /= (8*100); return sum;

8 Vector/Deque/String Suggestions When ou pass a vector, deque, or even C++ string to a function a deep cop will be made which takes time Copies ma be desirable in a situation to make sure the function alter our cop of the vector/deque/string But passing b const reference saves time and provide the same securit. #include <iostream> #include <vector> using namespace std; vector<int> m_vec; for(int i=0; i < 5; i++) // m_vec[i] = i+50; // doesn t work m_vec.push_back(i+50); // can mvec be different upon return? do_something1(mvec); // can mvec be different upon return? do_something2(mvec); void do_something1(vector<int> v) // process v; void do_something2(const vector<int>& v) // process v;

9 Reference Gotchas! Returning a reference to a dead variable (i.e. a local variable of a function that just completed) avg was a local variable and thus was deallocated when process_it completed class GradeBook public: int grades[8][100]; ; GradeBook gb; double& average = process_it(gb); cout << Avg: << average << endl; // Possible seg. fault / prog. crash double& process_it(const GradeBook &mgb) double avg = 0; for(int i=0; i < 8; i++) for(int j=0; j < 100; j++) avg += mgb.grades[i][j]; avg /= (8*100); return avg; // reference to avg // is returned...

MORE C++ REFERENCE FACTS 10

11 Using C++ References Mainl used for parameters, but can use it within the same function A variable declared with an int & doesn t store an int, but stores a reference/alias for an actual integer MUST assign to the reference variable when ou declare it. With Pointers With References - Phsicall 0x1a0 3 0x1a0 3 With References - Logicall 3 x int = 3, *ptr; ptr = &; // address-of // operator int &z; // NO! must assign int &x = ; // reference // declaration // we ve not copied // into x // we ve created an alias x++; // just got incr. cout << << endl; ptr x 0x1a0 0x1a0 Output: =4 in both programs