CSE 332: C++ functions Review: What = and & Mean In C++ the = symbol means either initialization or assignment –If it’s used with a type declaration, it.

Slides:



Advertisements
Similar presentations
Constructor. 2 constructor The main use of constructors is to initialize objects. A constructor is a special member function, whose name is same as class.
Advertisements

Chapter 9 Pointers and Dynamic Arrays. Overview 9.1 Pointers 9.2 Dynamic Arrays.
F UNCTION O VERLOADING Chapter 5 Department of CSE, BUET 1.
Templated Functions. Overloading vs Templating  Overloaded functions allow multiple functions with the same name.
CSE 332: C++ exceptions Overview of C++ Exceptions Normal program control flow is halted –At the point where an exception is thrown The program call stack.
This Time Pointers (declaration and operations) Passing Pointers to Functions Const Pointers Bubble Sort Using Pass-by-Reference Pointer Arithmetic Arrays.
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.
6/10/2015C++ for Java Programmers1 Pointers and References Timothy Budd.
1 6/20/2015CS150 Introduction to Computer Science 1 Functions Chapter 6, 8.
CS-341 Dick Steflik Introduction. C++ General purpose programming language A superset of C (except for minor details) provides new flexible ways for defining.
Pointers: Part I. Why pointers? - low-level, but efficient manipulation of memory - dynamic objects  Objects whose memory is allocated during program.
Review on pointers and dynamic objects. Memory Management  Static Memory Allocation  Memory is allocated at compiling time  Dynamic Memory  Memory.
1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation –The new operator –The delete operator –Dynamic.
1 Procedural Concept The main program coordinates calls to procedures and hands over appropriate data as parameters.
CSE 425: Object-Oriented Programming II Implementation of OO Languages Efficient use of instructions and program storage –E.g., a C++ object is stored.
CSE 332: C++ templates This Week C++ Templates –Another form of polymorphism (interface based) –Let you plug different types into reusable code Assigned.
Variables, Functions & Parameter Passing CSci 588 Fall 2013 All material not from online sources copyright © Travis Desell, 2011.
CSC 221: Computer Programming I Fall 2001  top-down design  approach to problem solving, program design  focus on tasks, subtasks, …  reference parameters.
Recursion Textbook chapter Recursive Function Call a recursive call is a function call in which the called function is the same as the one making.
CSE 332: C++ debugging in Eclipse C++ Debugging in Eclipse We’ve now covered several key program features –Variable declarations, expressions and statements.
CSE 232: C++ pointers, arrays, and references Overview of References and Pointers Often need to refer to another object –Without making a copy of the object.
Defining and Converting Data Copyright Kip Irvine, 2003 Last Update: 11/4/2003.
Parameter Passing Mechanisms Reference Parameters Read § §
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 7 Clicker Questions September 22, 2009.
Parameter Passing Mechanisms Reference Parameters § §
Pointers and Dynamic Memory Allocation Copyright Kip Irvine 2003, all rights reserved. Revised 10/28/2003.
Chapter 8 Scope of variables Name reuse. Scope The region of program code where it is legal to reference (use) a variable The scope of a variable depends.
Overloading Operator MySting Example. Operator Overloading 1+2 Matrix M 1 + M 2 Using traditional operators with user-defined objects More convenient.
COMPUTER PROGRAMMING. Functions’ review What is a function? A function is a group of statements that is executed when it is called from some point of.
CSE 332: C++ debugging Why Debug a Program? When your program crashes –Finding out where it crashed –Examining program memory at that point When a bug.
CSIS 113A Lecture 8 Parameters.  Two methods of passing arguments as parameters  Call-by-value  ‘copy’ of value is passed  Call-by-reference  ‘address.
Copyright 2005, The Ohio State University 1 Pointers, Dynamic Data, and Reference Types Review on Pointers Reference Variables Dynamic Memory Allocation.
Tracing through E01, question 9 – step 1 // p02.cc P. Conrad, for CISC181 07S // Exam question for E01 #include using namespace std; void mysteryFunction(int.
CS 376b Introduction to Computer Vision 01 / 23 / 2008 Instructor: Michael Eckmann.
Lecture 3 Classes, Structs, Enums Passing by reference and value Arrays.
Pointers A pointer is a variable that contains a memory address as it’s value. The memory address points to the actual data. –A pointer is an indirect.
Lecture 6 C++ Programming Arne Kutzner Hanyang University / Seoul Korea.
CSE 232: C++ memory management Overview of Arrays Arrays are the simplest kind of data structure –One item right after another in memory (“contiguous range”
Review 1 List Data Structure List operations List Implementation Array Linked List.
C++ Programming Lecture 17 Pointers – Part I The Hashemite University Computer Engineering Department (Adapted from the textbook slides)
Lecture 7 Pointers & Refrence 1. Background 1.1 Variables and Memory  When you declare a variable, the computer associates the variable name with a particular.
CSE 332: C++ Statements C++ Statements In C++ statements are basic units of execution –Each ends with ; (can use expressions to compute values) –Statements.
Functions Illustration of: Pass by value, reference Scope Allocation Reference: See your CS115/215 textbook.
Functions, Scope, and The Free Store Functions Functions must be declared by a function prototype before they are invoked, return_type Function_name(type,
Pointers It provides a way of accessing a variable without referring to its name. The mechanism used for this is the address of the variable.
System Programming Practical Session 7 C++ Memory Handling.
Object-Oriented Programming in C++ Lecture 4 Constants References Operator overloading.
1 Reference Variables Chapter 8 Page Reference Variables Safer version of C/C++ pointer. "Refers to" a variable. Like a pointer. Effectively.
CSE 332: C++ pointers, arrays, and references Overview of Pointers and References Often need to refer to another object –Without making a copy of the object.
Array and Pointers An Introduction Unit Unit Introduction This unit covers the usage of pointers and arrays in C++
CSE 332: C++ expressions Expressions: Operators and Operands Operators obey arity, associativity, and precedence int result = 2 * 3 + 5; // assigns 11.
Lecture 9 – Array (Part 2) FTMK, UTeM – Sem /2014.
Current Assignments Project 3 has been posted, due next Tuesday. Write a contact manager. Homework 6 will be posted this afternoon and will be due Friday.
 2000 Prentice Hall, Inc. All rights reserved Program Components in C++ Function definitions –Only written once –These statements are hidden from.
C++ Functions A bit of review (things we’ve covered so far)
1 This week Basics of functions Stack frames Stack vs. Heap (brief intro) Calling conventions Storage classes vs. scope Library functions Overloading.
C++ Programming Lecture 13 Functions – Part V By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department.
Pointers A variable that holds an address value is called a pointer variable, or simply a pointer.  What is the data type of pointer variables? It’s not.
CSE 332: C++ Exceptions Motivation for C++ Exceptions Void Number:: operator/= (const double denom) { if (denom == 0.0) { // what to do here? } m_value.
CSE 332: Scientific debugging in C++ Scientific Debugging in C++ (with Eclipse & gdb) By now we’ve covered several key C++ features –Variable declarations.
Overview 4 major memory segments Key differences from Java stack
Motivation and Overview
Student Book An Introduction
Overview 4 major memory segments Key differences from Java stack
Pointers, Dynamic Data, and Reference Types
Dynamic Memory A whole heap of fun….
C++ Pointers and Strings
Pointers and dynamic objects
The Stack.
C++ Pointers and Strings
Presentation transcript:

CSE 332: C++ functions Review: What = and & Mean In C++ the = symbol means either initialization or assignment –If it’s used with a type declaration, it means initialization –If it’s used without a type declaration, it means assignment int j(7); // j is initialized with value 7 int k = 4; // k is initialized with value 4 j = 3; // j is assigned value 3 In C++ the & symbol also has a similar “dual nature” –If it’s used inside a type declaration, it means a reference (an alias) Arguments to function are always declared along with their types –If it’s used outside a type declaration, it means “address of” int swap (int & i, int & j); // references to int int & s = j; // reference s initialized to refer to j int * p = & j; // pointer p initialized w/ j’s address

CSE 332: C++ functions Review: Parameter/Variable Declarations Hint: read parameter and variable declarations right to left int i; “ i is an integer” int & r = i; “ r is a reference to an integer (initialized with i)” int * p; “ p is a pointer to an integer” int * & q = p; “ q is a reference to a pointer to an integer (initialized with p)” Read function declarations inside out “function main takes an integer and an array of pointers to char, and returns an integer” int main (int argc, char * argv[]); “function usage takes a pointer to char, and returns void (nothing)” void usage (char * program_name); “function setstring takes a reference to a (C++) string, and returns void” void setstring (string & s);

CSE 332: C++ functions How Function Calls Work A function call uses the “program call stack” 1.Stack frame is “pushed” when the call is made 2.Execution jumps to the function’s code block 3.Function’s code block is executed 4.Execution returns to just after where call was made 5.Stack frame is “popped” (variables in it destroyed) This incurs a (small) performance cost –Copying arguments, other info into the stack frame –Stack frame management –Copying function result back out of the stack frame

CSE 332: C++ functions Review: Pass By Value void foo () { int i = 7; baz (i); } void baz (int j) { j = 3; } 7 7 → 3 local variable i (stays 7) parameter variable j (initialized with the value passed to baz, and then is assigned the value 3) Think of this as declaration with initialization, along the lines of: int j = what baz was passed;

CSE 332: C++ functions Review: Pass By Reference void foo () { int i = 7; baz (i); } void baz (int & j) { j = 3; } 7 → 3 local variable i j is initialized to refer to the variable that was passed to baz: when j is assigned 3, the passed variable is assigned 3. 7 → 3 again declaration with initialization int & j = what baz was passed; argument variable j

CSE 332: C++ functions What About Pointers as By-Value Arguments? void foo () { int i = 7; baz (&i); } void baz (int * j) { *j = 3; } 7 → 3 local variable i dereferencing j gives the location to which it points, so the variable whose address was passed is assigned 3. argument variable j 0x74bead00 dereference operator address-of operator j is initialized with the address (value) that was passed to baz

CSE 332: C++ functions What About Passing Pointers By-Reference? void foo () { int i = 7; int j = 4; int *p = &i; baz (p, j); } void baz (int * & q, int & k) { q = &k; } 7 local variable i q references p and k references j: when q is assigned the address of k, the effect is to make p point to j instead of i argument variable q 4 local variable j 0x74bead04 argument variable k 0x74bead00 &i → &k

CSE 332: C++ functions Pass By const Reference void foo () { int i = 7; baz (i); } void baz (const int & j) { cout << j << endl; } 7 local variable i j is initialized to refer to the variable that was passed to baz: j can not be changed. 7 again declaration with initialization Const int & j = what baz was passed; and it is read only. argument variable j

CSE 332: C++ functions Default Arguments Some functions can take several arguments –Can increase function flexibility –Can reduce proliferation of near-identical functions But, callers must supply all of these arguments –Even for ones that aren’t “important” We can provide defaults for some arguments –Caller doesn’t have to fill these in

CSE 332: C++ functions Required vs. Default Arguments Function with required argument // call as foo(2); (prints 2) void foo(int a); void foo(int a) {cout << a << endl;} Function with default argument –Notice only the declaration gives the default value // can call as foo(2); (prints 2) // or can call as foo(); (prints 3) void foo(int a = 3); void foo(int a) {cout << a << endl;}

CSE 332: C++ functions Defaults with Multiple Arguments Function with one of two arguments defaulted // can call as foo(2); (prints 2 3) // or can call as foo(2, 4); (prints 2 4) void foo(int a, int b = 3); void foo(int a, int b) {cout << a << “ ” << b << endl;} Same function, with both arguments defaulted // can call as foo(); (prints 1 3) // or can call as foo(2); (prints 2 3) // or can call as foo(2, 4); (prints 2 4) void foo(int a = 1, int b = 3); void foo(int a, int b) {cout << a << “ ” << b << endl;}

CSE 332: C++ functions Default Argument Limitations Watch out for ambiguous signatures –foo(); and foo(int a = 2); for example Can only default the rightmost arguments –Can’t declare void foo(int a = 1, int b); Caller must supply leftmost arguments –Even if they’re the same as the defaults

CSE 332: C++ functions Varying Parameters initializer_list parameters; void foo(initializer_list coffee){ for (auto beg = coffee.begin(); beg != coffee.end(); ++beg) { cout << *beg << “ ”; } cout << endl; } //print out all 4 coffees foo(“latte”, “mocha”, “eggnog latte”, “peppermint mocha”); //print out only 2 coffees foo(“latte”, “mocha”);

CSE 332: C++ functions Function Overload // can call errMsg with 1 or 2 integers or a string void errMsg(int & errCode) {cout << “Error code is: ” << errCode<< endl;} void errMsg(const int & errCode) {cout << “Error code is: ” << errCode<< endl;} void errMsg(int & errCode, string msg) {cout << “Error --” << msg << “Error code: ” errCode << endl;} Void errMsg(string msg) {cout << “Error --” << msg << endl;} int err5 = 5; err1 = 1; const int outOfRange = 3; errMsg (err5); errMsg (err1, “can’t open file”); errMsg (“dividing by 0”); errMsg (outOfRange);