Calling the Function. Two Function Declarations Here is a function declared as pass by value. Why use Pass By Reference?



Similar documents
Comp151. Definitions & Declarations

Boolean Expressions, Conditions, Loops, and Enumerations. Precedence Rules (from highest to lowest priority)

Name: Class: Date: 9. The compiler ignores all comments they are there strictly for the convenience of anyone reading the program.

What is a Loop? Pretest Loops in C++ Types of Loop Testing. Count-controlled loops. Loops can be...

COSC 181 Foundations of Computer Programming. Class 6

Chapter 8 Selection 8-1

C++ INTERVIEW QUESTIONS

Chapter 5 Functions. Introducing Functions

Basics of I/O Streams and File I/O

6. Control Structures

Moving from CS 61A Scheme to CS 61B Java

Computer Programming C++ Classes and Objects 15 th Lecture

Operator Overloading. Lecture 8. Operator Overloading. Running Example: Complex Numbers. Syntax. What can be overloaded. Syntax -- First Example

Common Beginner C++ Programming Mistakes

Appendix K Introduction to Microsoft Visual C++ 6.0

Storage Classes CS 110B - Rule Storage Classes Page 18-1 \handouts\storclas

13 Classes & Objects with Constructors/Destructors

Moving from C++ to VBA

PART-A Questions. 2. How does an enumerated statement differ from a typedef statement?

9 Control Statements. 9.1 Introduction. 9.2 Objectives. 9.3 Statements

MS Visual C++ Introduction. Quick Introduction. A1 Visual C++

Lecture 3. Arrays. Name of array. c[0] c[1] c[2] c[3] c[4] c[5] c[6] c[7] c[8] c[9] c[10] c[11] Position number of the element within array c

PIC 10A. Lecture 7: Graphics II and intro to the if statement

Chapter One Introduction to Programming

Lecture 2 Notes: Flow of Control

Conditions & Boolean Expressions

The C++ Language. Loops. ! Recall that a loop is another of the four basic programming language structures

Sources: On the Web: Slides will be available on:

Passing 1D arrays to functions.

Member Functions of the istream Class

7.7 Case Study: Calculating Depreciation

While Loop. 6. Iteration

Chapter 5. Selection 5-1

1. The First Visual C++ Program

Scoping (Readings 7.1,7.4,7.6) Parameter passing methods (7.5) Building symbol tables (7.6)

Introduction to Programming (in C++) Loops. Jordi Cortadella, Ricard Gavaldà, Fernando Orejas Dept. of Computer Science, UPC

Example. Introduction to Programming (in C++) Loops. The while statement. Write the numbers 1 N. Assume the following specification:

Arrays. number: Motivation. Prof. Stewart Weiss. Software Design Lecture Notes Arrays

Phys4051: C Lecture 2 & 3. Comment Statements. C Data Types. Functions (Review) Comment Statements Variables & Operators Branching Instructions

IS0020 Program Design and Software Tools Midterm, Feb 24, Instruction

Introduction to Python

For the next three questions, consider the class declaration: Member function implementations put inline to save space.

Chapter 9 Delegates and Events

CpSc212 Goddard Notes Chapter 6. Yet More on Classes. We discuss the problems of comparing, copying, passing, outputting, and destructing

QUIZ-II QUIZ-II. Chapter 5: Control Structures II (Repetition) Objectives. Objectives (cont d.) 20/11/2015. EEE 117 Computer Programming Fall

16. Recursion. COMP 110 Prasun Dewan 1. Developing a Recursive Solution

PROBLEM SOLVING SEVENTH EDITION WALTER SAVITCH UNIVERSITY OF CALIFORNIA, SAN DIEGO CONTRIBUTOR KENRICK MOCK UNIVERSITY OF ALASKA, ANCHORAGE PEARSON

C++ Programming: From Problem Analysis to Program Design, Fifth Edition. Chapter 3: Input/Output

Chapter 9 Text Files User Defined Data Types User Defined Header Files

EP241 Computer Programming

Ch 7-1. Object-Oriented Programming and Classes

COMPUTER SCIENCE 1999 (Delhi Board)

Embedded Systems. Review of ANSI C Topics. A Review of ANSI C and Considerations for Embedded C Programming. Basic features of C

arrays C Programming Language - Arrays

Visual Studio 2008 Express Editions

Data Structures using OOP C++ Lecture 1

CSI33 Data Structures

Class 16: Function Parameters and Polymorphism

CSCI 123 INTRODUCTION TO PROGRAMMING CONCEPTS IN C++

if and if-else: Part 1

Embedded SQL. Unit 5.1. Dr Gordon Russell, Napier University

Object Oriented Software Design II

Compiler Construction

Object Oriented Software Design

Course: Programming II - Abstract Data Types. The ADT Stack. A stack. The ADT Stack and Recursion Slide Number 1

AP Computer Science Java Subset

C++ Outline. cout << "Enter two integers: "; int x, y; cin >> x >> y; cout << "The sum is: " << x + y << \n ;

C++ Crash Kurs. C++ Object-Oriented Programming

C++FA 3.1 OPTIMIZING C++

Object Oriented Software Design II

VB.NET Programming Fundamentals

Appendix M: Introduction to Microsoft Visual C Express Edition

Multichoice Quetions 1. Atributes a. are listed in the second part of the class box b. its time is preceded by a colon. c. its default value is

C++ Language Tutorial

C++FA 5.1 PRACTICE MID-TERM EXAM

Syllabus OBJECT ORIENTED PROGRAMMING C++

El Dorado Union High School District Educational Services

10CS35: Data Structures Using C

Debugging. Common Semantic Errors ESE112. Java Library. It is highly unlikely that you will write code that will work on the first go

Java Interview Questions and Answers

Short Notes on Dynamic Memory Allocation, Pointer and Data Structure

The Payroll Program. Payroll

What Is Recursion? 5/12/10 1. CMPSC 24: Lecture 13 Recursion. Lecture Plan. Divyakant Agrawal Department of Computer Science UC Santa Barbara

An Incomplete C++ Primer. University of Wyoming MA 5310

Getting Started with the Internet Communications Engine

The if Statement and Practice Problems

Recursion. Slides. Programming in C++ Computer Science Dept Va Tech Aug., Barnette ND, McQuain WD

C++ Input/Output: Streams

High-Level Programming Languages. Nell Dale & John Lewis (adaptation by Michael Goldwasser)

Why using ATmega16? University of Wollongong Australia. 7.1 Overview of ATmega16. Overview of ATmega16

CS 241 Data Organization Coding Standards

COMP 110 Prasun Dewan 1

Answers to Review Questions Chapter 7

Cultural Relativism. 1. What is Cultural Relativism? 2. Is Cultural Relativism true? 3. What can we learn from Cultural Relativism?

CS193D Handout 06 Winter 2004 January 26, 2004 Copy Constructor and operator=

Transcription:

Functions in C++ Let s take a look at an example declaration: Lecture 2 long factorial(int n) Functions The declaration above has the following meaning: The return type is long That means the function will return a long integer to the calling function The name of the function is factorial When we need to call this function we will use this name The function takes one parameter which is an integer variable named n Functions in C++ How might our factorial function be implemented? long factorial(int n) long result = 1, k = n; while(k > 1) result *= k--; return result; Note the use of the post-decrement operator Why do we use postfix here instead of prefix? Note the use of return to return the value to the caller Functions in C++ How might we call our function from a main() function? #include <iostream> long factorial(int); // forward declaration int x; cout << Please enter a number> << endl; cin >> x; cout << x <<! is << factorial(x) << endl; Note forward declaration Needed only if factorial() appears below main() in the file Parameter names do not need to be specified but all types must! Function call--an expression which evaluates to its return value Could also be used in assignment Argument Passing Demonstration #1 The factorial function There are two ways to pass arguments to functions in C++: Pass by VALUE Pass by REFERENCE Pass by VALUE The value of a variable is passed along to the function If the function modifies that value, the modifications stay within the scope of that function Pass by REFERENCE A reference to the variable is passed along to the function If the function modifies that value, the modifications appear also within the scope of the calling function 1

Two Function Declarations Here is a function declared as pass by value // pass by value x *= x; // remember, this is like x = x * x; return x; Now here is the same function declared as pass by reference long squareit(long &x) // pass by reference x *= x; // remember, this is like x = x * x; return x; What s the difference? Calling the Function #include <iostreams> long y; cout << Enter a value to be squared> ; cin >> y; long result = squareit(y); cout << y << squared is << result << endl; Suppose the user enters the number 7 as input When squareit() is declared as pass by value, the output is: 7 squared is 49 When squareit() is declared as pass by reference, the output is: 49 squared is 49 Let s see for ourselves Demonstration #2 Pass by Value vs Pass by Reference Because you really want changes made to a parameter to persist in the scope of the calling function The function call you are implementing needs to initialize a given parameter for the calling function You need to return more than one value to the calling function Because you are passing a large structure A large structure takes up stack space Passing by reference passes merely a reference (pointer) to the structure, not the structure itself Let s look at these two reasons individually Because you want to return two values void gettimeandtemp(string &time, string &temp) time = queryatomicclock(); // made up func temp = querylocaltemperature(); // made up func All the caller would need to do now is provide the string variables string thetime, thetemp; gettimeandtemp(thetime,thetemp); cout << The time is: << thetime << endl; cout << The temperature is: << thetemp << endl; Because you are passing a large structure: void initdatatype(bigdatatype &arg1) arg1field1 = 0; arg1field2 = 1; // etc, etc, assume BIGDataType has // lots of fields initdatatype is an arbitrary function used to initialize a variable of type BIGDataType Assume BIGDataType is a large class or structure With Pass by Reference, only a reference is passed to this function (instead of throwing the whole chunk on the stack) 2

But be careful bool isbusy(bigdatatype &arg1) if (arg1busyfield = 0) return true; return false; You can specify that a parameter cannot be modified: bool isbusy(const BIGDataType &arg1) if (arg1busyfield = 0) return true; return false; Recognize the familiar bug? What s worse is that you ve mangled the data type in the scope of the calling function as well! Can you protect against this? By adding the const keyword in front of the argument declaration, you tell the compiler that this parameter must not be changed by the function Any attempts to change it will generate a compile time error Demonstration #3 Pass by Reference (with and without the const keyword) OK, we ve used the s word a few times already today What does it mean? can be defined as a range of lines in a program in which any variables that are defined remain valid delimiters are the curly braces and delimiters are usually encountered: At the beginning and end of a function definition In switch statements In loops and if/else statements In class definitions (coming soon!) All by themselves in the middle of nowhere Wait, what was that last one????? Delimiters may appear by themselves int x = 0,y = 1, k = 5; int x = 1; When you have multiple scopes in the same function you may access variables in any of the parent scopes You may also declare a variable with the same name as one in a parent scope The local declaration takes precedence int x = 0,y = 1; int x = 1, k = 5; What is wrong here? You may only access variables that are declared in the current scope or above 3

There is a global scope int globalx = 0; int x = 0,y = 1,k = 5; int x = 1; globalx = 10; cout << globalx is << globalx << endl; Demonstration #4 Miscellaneous Issues What happens here? Function Declarations vs Definitions We ve been somewhat lax about this long squareit(long); return( x * x ); // Declaration (or prototype) // Definition Before a function may be called by any other function it must be either defined or declared When a function is declared separately from its definition, this is called a forward declaration Forward declarations need only to specify return type and parameter type Parameter names are irrelevant What happens when programs start getting really big? We naturally want to separate all the functions we implement into logical groupings These groupings are usually stored in their own files How, then, do we access a function from one file when we are working in another file? We move the function declarations into header files Then all we need to do is include the appropriate header file in whatever source file needs it By convention, the function definitions go into a source file with a cpp suffix, whereas function declarations go into a source file with a h suffix Consider the following example // mymathh -- header file for math functions long squareit(long); // mymathcpp -- implementation of math functions // maincpp #include mymathh cout >> 5 squared is >> squareit(5) >> endl; MAINCPP #include MyMathh int x=squareit(5); cout << x << endl; MYMATHCPP MYMATHH ; We start out with three files When the compiler begins compiling MAINCPP, it will include the MYMATHH header file 4

MAINCPP MYMATHH ; int x=squareit(5); cout << x << endl; MYMATHCPP When the compiler begins compiling MAINCPP, the contents of MYMATHH are actually drawn in to the MAINCPP file The compiler sees the declaration of squareit() from MYMATHH and so is happy when it comes time to compile the call to squareit() In the main() function 5