More Functions. Pass by Value. Example: Exchange two numbers. Storage Classes. Passing Parameters by Reference. Pass by value and by reference

Similar documents
Functions and Recursion

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

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

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

C++ As A "Better C" Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan.

Chapter 15 - C++ As A "Better C"

Outline. Introduction. Arrays declarations and initialization. Const variables. Character arrays. Static arrays. Examples.

Kingdom of Saudi Arabia Princes Nora bint Abdul Rahman University College of Computer Since and Information System CS242 ARRAYS

엄현상 (Eom, Hyeonsang) School of Computer Science and Engineering Seoul National University COPYRIGHTS 2017 EOM, HYEONSANG ALL RIGHTS RESERVED

University of Kelaniya Sri Lanka

Introduction to C++ (Extensions to C)

Chapter 3 - Functions

Programming in C++: Assignment Week 8

Topics. Functions. Functions

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

CSCE Practice Midterm. Data Types

TEMPLATE IN C++ Function Templates

Object Oriented Design

Chapter 3 - Functions

Chapter 4 - Arrays. 4.1 Introduction. Arrays Structures of related data items Static entity (same size throughout program) A few types

W3101: Programming Languages C++ Ramana Isukapalli

Chapter 3 - Functions. Chapter 3 - Functions. 3.1 Introduction. 3.2 Program Components in C++

The C++ Language. Arizona State University 1

Introduction to C++ Systems Programming

1- Write a single C++ statement that: A. Calculates the sum of the two integrates 11 and 12 and outputs the sum to the consol.

Chapter 4 - Arrays. 4.1 Introduction. Arrays Structures of related data items Static entity (same size throughout program)

Homework 4. Any questions?

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

Exercise 1.1 Hello world

Function Overloading

CSCE 206: Structured Programming in C++

CS242 COMPUTER PROGRAMMING

Pointers, Dynamic Data, and Reference Types

Arrays. Week 4. Assylbek Jumagaliyev

Non-numeric types, boolean types, arithmetic. operators. Comp Sci 1570 Introduction to C++ Non-numeric types. const. Reserved words.

Chapter 7 - Notes User-Defined Functions II

C Functions. Object created and destroyed within its block auto: default for local variables

(5-1) Object-Oriented Programming (OOP) and C++ Instructor - Andrew S. O Fallon CptS 122 (February 4, 2019) Washington State University

Week 3: Pointers (Part 2)

Functions that Return a Value. Approximate completion time Pre-lab Reading Assignment 20 min. 92

Lab Instructor : Jean Lai

Implementing an ADT with a Class

CS 376b Computer Vision

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

Multiple Choice (Questions 1 13) 26 Points Select all correct answers (multiple correct answers are possible)

A Tour of the C++ Programming Language

Why Pointers. Pointers. Pointer Declaration. Two Pointer Operators. What Are Pointers? Memory address POINTERVariable Contents ...

CSCE Practice Midterm. Data Types

Lecture 8: Object-Oriented Programming (OOP) EE3490E: Programming S1 2017/2018 Dr. Đào Trung Kiên Hanoi Univ. of Science and Technology

CAAM 420 Fall 2012 Lecture 29. Duncan Eddy

Functions, Arrays & Structs

EECS402 Lecture 02. Functions. Function Prototype

The American University in Cairo Department of Computer Science & Engineering CSCI &09 Dr. KHALIL Exam-I Fall 2011

Computer Programming

Chapter 2. Procedural Programming

struct Buffer { Buffer(int s) { buf = new char[s]; } ~Buffer() { delete [] buf; } char *buf; };

WARM UP LESSONS BARE BASICS

A Tour of the C++ Programming Language

Programmer-Defined Functions

Basic program The following is a basic program in C++; Basic C++ Source Code Compiler Object Code Linker (with libraries) Executable

Introduction to C++ Introduction to C++ 1

BITG 1233: Introduction to C++

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

Fast Introduction to Object Oriented Programming and C++

Introduction to Programming

Scope. Scope is such an important thing that we ll review what we know about scope now:

Intermediate Programming, Spring 2017*

CSE 2421: Systems I Low-Level Programming and Computer Organization. Functions. Presentation C. Predefined Functions

Functions, Arrays & Structs

Computing and Statistical Data Analysis Lecture 3

Arrays. Outline. Multidimensional Arrays Case Study: Computing Mean, Median and Mode Using Arrays Prentice Hall, Inc. All rights reserved.

C++ Basics. Data Processing Course, I. Hrivnacova, IPN Orsay

The University Of Michigan. EECS402 Lecture 02. Andrew M. Morgan. Savitch Ch. 3-4 Functions Value and Reference Parameters.

COMP322 - Introduction to C++

C++ Namespaces, Exceptions

CS 251 INTERMEDIATE SOFTWARE DESIGN SPRING C ++ Basics Review part 2 Auto pointer, templates, STL algorithms

Tutorial 13 Salary Survey Application: Introducing One- Dimensional Arrays

Short Notes of CS201

Engineering Problem Solving with C++, 3e Chapter 2 Test Bank

Object Reference and Memory Allocation. Questions:

Variable Definitions and Scope

Chapter 4 - Notes Control Structures I (Selection)

Lecture 23: Pointer Arithmetic

1/29/2011 AUTO POINTER (AUTO_PTR) INTERMEDIATE SOFTWARE DESIGN SPRING delete ptr might not happen memory leak!

CS201 - Introduction to Programming Glossary By

CSE 374 Programming Concepts & Tools. Hal Perkins Spring 2010

Your first C++ program

CE221 Programming in C++ Part 1 Introduction

Object-Oriented Programming in C++

ENERGY 211 / CME 211. Functions

IS 0020 Program Design and Software Tools

CMPS 221 Sample Final

Pointers. Variable Declaration. Chapter 10

C++ Programming: From Problem Analysis to Program Design, Third Edition

Review. Modules. CS 151 Review #6. Sample Program 6.1a:

CS24 Week 3 Lecture 1

calling a function - function-name(argument list); y = square ( z ); include parentheses even if parameter list is empty!

CSE 374 Programming Concepts & Tools. Hal Perkins Fall 2015 Lecture 19 Introduction to C++

Lecture on pointers, references, and arrays and vectors

Fundamentals of Programming Session 12

Transcription:

Pass by Value More Functions Different location in memory Changes to the parameters inside the function body have no effect outside of the function. 2 Passing Parameters by Reference Example: Exchange two numbers If we use pass by value, it will not work!!! To have a function with multiple outputs, we have to use pass by reference. Reference (address) of parameter is passed to the function, instead of its value. If the function changes the parameter value, the changes will be reflected in the program calling it. How to pass parameters by reference: <type>& <variable>,..., <type>& <variable> a and num1 are in the same location in memory Also b and num2 3 Pass by value and by reference 5 Storage Classes Storage class specifiers Storage class Where object exists in memory Scope Where object is referenced in program Linkage Where an identifier is known Automatic storage Object created and destroyed within its block auto Default for local variables. Example: auto float x, y; register Tries to put variables into high-speed registers Can only be used with local variables and parameters 6 1

Storage Class Each variable has a storage class. Determines the period during which the variable exists in memory. Some variables are created only once (memory is set aside to hold the variable value) Global variables are created only once. Some variables are re-created many times Local variables are re-created each time a function is called. Block Scope int main(void) int y; int a = y; cout << a << endl; cout << a << endl; Error a doesn t exist outside the block! 7 8 Storage Classes Static storage Variables exist for entire program execution static Local variables defined in functions Keep value after function ends Only known in their own function Extern Default for global variables and functions. Known in any function Specifying Storage Class auto int j; register int i_need_to_be_fast; static char remember_me; extern double a_global; 9 10 Lifetime of Local Automatic Variables Their storage is created (allocated) when control enters the function Local variables are alive while function is executing Their storage is destroyed (deallocated) when function exits Lifetime of Global Variables Their lifetime is the lifetime of the entire program Their memory is allocated when program begins execution Their memory is deallocated when the entire program terminates 11 12 2

Automatic vs. Static Variable Storage for automatic variable is allocated at block entry and deallocated at block exit Storage for static variable remains allocated throughout execution of the entire program Default Allocation Local variables are automatic To obtain a static local variable, you must use the reserved word static in its declaration 13 1 Static and Automatic Local Variables int popularsquare(int n) static int timescalled = 0; // Initialized only once int result = n * n; // Initialized each time timescalled = timescalled + 1; cout << Call # << timescalled << endl; return result; static example int countcalls(void) static int count = 0; count++; return(count); cout << countcalls() << endl; cout << countcalls() << endl; cout << countcalls() << endl; 15 15 16 Scope of Identifier The scope of an identifier (or named constant) is the region of program code in which it is legal to use that identifier for any purpose Local Scope The scope of an identifier that is declared inside a block (this includes function parameters) extends from the point of declaration to the end of the block vs. Global Scope The scope of an identifier that is declared outside of all namespaces, functions, and classes extends from point of declaration to the end of the entire file containing the program code 17 18 3

const float TAX_RATE = 0.05; // Global constant float tiprate; // Global variable void handle (int, float); // Function prototype using namespace std; int main () int age; // age and bill local to this block float bill;. // a, b, and tax are local to main. // TAX_RATE and tiprate can be used handle (age, bill); return 0; void handle (int a, float b) float tax; // a, b, and tax local to this block. // age and bill if used must be declared as local to handle. // TAX_RATE and tiprate can be used Scope Rules 1 Function names have global scope 2 A function parameter s scope is identical to the scope of a local variable declared in the outermost block of the function body 3 A global variable s (or constant s) scope extends from its declaration to the end of the file. A local variable s (or constant s) scope extends from its declaration to the end of the block in which it is declared, including any nested blocks. 19 19 20 1 // Example 1 2 // A scoping example 3 #include <iostream> 5 using std::cout; 6 using std::endl; 7 8 void a( void ); // function prototype 9 void b( void ); // function prototype 10 void c( void ); // function prototype 11 x is different inside and outside 12 int x = 1; // global variable the block. 13 1 int main() 15 16 int x = 5; // local variable to main 17 18 cout << "local x in outer scope of main is " << x << endl; 19 20 21 // int x = 7; start new scope 1. Function prototypes 22 23 cout << "local in inner scope of main is " << x << endl; x 2 // end new scope 25 26 cout << "local x in outer scope of main is " << x << endl; 27 28 a(); // a has automatic local x 29 b(); // b has static local x local x in outer scope of main is 5 30 c(); // c uses global x local x in inner scope of main is 7 31 a(); // a reinitializes automatic local x in local outer x scope of main is 5 32 b(); // static local x retains its previous value 33 c(); // global 1.2 x also Initialize retains its value local variable 3 1.1 Initialize global variable 35 cout << "local x in main is " << x << endl; 36 37 return 0; Local automatic variables are 38 39 created and destroyed each 0 void a( void ) time a is called. 1 2 int x = 25; // initialized each time a is called 3 cout << endl << "local x in a is " << x 5 << " after entering a" << endl; local x in a is 25 after entering a 6 ++x; local x in a is 26 before exiting a 7 cout << "local x in a is " << x 8 << " before exiting a" << endl; 9 50 51 void b( void ) 52 Local static variables are 53 static int x = 50; // Static initialization only not destroyed when the 5 // first time b is called. 55 cout << endl << "local static x is " << x function ends. 3.1 Define Functions 56 << " on entering b" << endl; 57 ++x; local static x is 50 on entering b 58 cout << "local static x is " << x local static x is 51 on exiting b 59 << " on exiting b" << endl; 60 61 Global variables are always 62 void c( void ) accessible. Function c 63 references the global x. 6 cout << endl << "global x is " << x global x is 1 on entering c 65 << " on entering c" << endl; 66 x *= 10; global x is 10 on exiting c 67 cout << "global x is " << x << " on exiting c" << endl; 68 Unary Scope Resolution Operator local x in outer scope of main is 5 local x in inner scope of main is 7 local x in outer scope of main is 5 local x in a is 25 after entering a local x in a is 26 before exiting a local static x is 50 on entering b local static x is 51 on exiting b global x is 1 on entering c global x is 10 on exiting c local x in a is 25 after entering a local x in a is 26 before exiting a local static x is 51 on entering b local static x is 52 on exiting b global x is 10 on entering c global x is 100 on exiting c local x in main is 5 Program Output Unary scope resolution operator (::) Access global variables if a local variable has same name not needed if names are different instead of variable use ::variable 2

1 // Example 2 2 // Using the unary scope resolution operator 3 #include <iostream> 5 using std::cout; 6 using std::endl; 7 8 #include <iomanip> 9 10 using std::setprecision; 11 12 const double PI = 3.1159265358979; 13 1 int main() 15 16 const float PI = static_cast< float >( ::PI ); 17 18 cout << setprecision( 20 ) 19 << " Local float value of PI = " << PI 20 << "\nglobal double value of PI = " << ::PI << endl; 21 22 return 0; 23 Local float value of PI = 3.115927101257322 Global double value of PI = 3.11592653589790007 Notice the use of :: Practical Use of Storage Class Local variables are auto by default. Global variables are static by default. Declaring a local variable as static means it will remember it s last value (it s not destroyed and recreated each time it s scope is entered). 26 Revisiting Motivation We already saw several mechanisms that can support having similar functions for handling various types: Macros: #define SWAP(a,b) Using function overloading we can implement several functions with the same name that differ only in the parameter s type. For example : swap() void swap(int& a, int& b) int temp = a; void swap(float& a, float& b) float temp = a; void swap(char*& a, char*& b) char* temp = a; Introduction It would be very beneficial if we could implement only one function which will describe the swap() function (which is similar to all types) and still work for every type. Using we can do just that Example: void swap(t& a, T& b) T temp = a; void main() int i=, j=9; swap(i, j); char* str1 = hello ; char* str2 = world ; Swap(str1, str2); The line informs the compiler that this is a template functions, including a general type T, and that it should unfold the function according to the various options, T will receive. copyrights Elhanan Borenstein How Does it work? A template function actually represents a collections of functions. For each (different) usage (activation of the function with a different type) of the function: the compiler will first create the appropriate copy of the function and then compile that copy Will that code work? void dosomething( int I ) T a, b; b = a = i; Guidelines The template function must be included (directly or through #include) in the file that makes use of it (WHY?) a.cpp b.cpp void Swap(T& a, T& b) a.cpp void Swap(T& a, T& b) a.h void Swap(T& a, T& b) void main() Swap(i, j); b.cpp void Swap(T& a, T& b) void main() Swap(i, j); b.cpp #include a.h void main() Swap(i, j); 5

Format More than one general type can be defined. For example: template<class key, class value> Using the name T, is optional Instead of <class T> we can also use <typename T> For each class T, only one type can be used when calling the function no casting 6