Lecture 2 Functions. Functions in C++ long factorial(int n) The return type is long. That means the function will return a long integer to the calling.

Slides:



Advertisements
Similar presentations
Introduction to C Programming
Advertisements

Chapter 7: User-Defined Functions II
Lecture 18 Templates, Part II. From Last Time: What is a Template? This is the “official” specification for a template. It says that to define a template.
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.
Functions Most useful programs are much larger than the programs that we have considered so far. To make large programs manageable, programmers modularize.
Lecture 3: Topics If-then-else Operator precedence While loops Static methods Recursion.
Computer Science 1620 Functions. Given a number n, the factorial of n, written n!, is computed as follows: note: 0! = 1 examples: n! = n x (n-1) x (n-2)
Pointers “Absolute C++” Section 10.1
Lecture 1 The Basics (Review of Familiar Topics).
 2003 Prentice Hall, Inc. All rights reserved. 1 Functions Modules: functions and classes Programs use new and “prepackaged” modules –New: programmer-defined.
1 Midterm Review COMP 102. Tips l Eat a light meal before the exam l NO electronic devices (including calculators, dictionaries, phones, pagers, etc.)
Lesson 6 Functions Also called Methods CS 1 Lesson 6 -- John Cole1.
1 Functions Modules: functions and classes Programs use new and “prepackaged” modules –New: programmer-defined functions, classes –Prepackaged: from the.
C++ Functions. 2 Agenda What is a function? What is a function? Types of C++ functions: Types of C++ functions: Standard functions Standard functions.
Functions in C. Function Terminology Identifier scope Function declaration, definition, and use Parameters and arguments Parameter order, number, and.
VARIABLES, TYPES, INPUT/OUTPUT, ASSIGNMENT OPERATION Shieu-Hong Lin MATH/CS Department Chapel.
Outlines Chapter 3 –Chapter 3 – Loops & Revision –Loops while do … while – revision 1.
© The McGraw-Hill Companies, 2006 Chapter 4 Implementing methods.
Copyright © 2012 Pearson Education, Inc. Chapter 6: Functions.
Project 1 Due Date: September 25 th Quiz 4 is due September 28 th Quiz 5 is due October2th 1.
Agenda Review C++ Library Functions Review User Input Making your own functions Exam #1 Next Week Reading: Chapter 3.
CPS120: Introduction to Computer Science Decision Making in Programs.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 6 September 17, 2009.
CPS120: Introduction to Computer Science Functions.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 7 Clicker Questions September 22, 2009.
Object-Oriented Programming in C++
CPS120: Introduction to Computer Science Lecture 14 Functions.
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.
Built-In and user-Defined functions Software Design Concepts Lecture IV Dr. Sothy Vignarajah.
C Functions Three major differences between C and Java functions: –Functions are stand-alone entities, not part of objects they can be defined in a file.
1 Announcements Note from admins: Edit.cshrc.solaris instead of.tcshrc Note from admins: Do not use delta.ece.
Structure Programming Lecture 8 Chapter 5&6 - Function – part I 12 December 2015.
Chapter 3 Part I. 3.1 Introduction Programs written in C ◦ All statements were located in function main Programs written in C++ ◦ Programs will consist.
Chapter Functions 6. Modular Programming 6.1 Modular Programming Modular programming: breaking a program up into smaller, manageable functions or modules.
Chapter 3 Functions. 2 Overview u 3.2 Using C++ functions  Passing arguments  Header files & libraries u Writing C++ functions  Prototype  Definition.
Chapter 6 Functions. Topics Basics Basics Simplest functions Simplest functions Functions receiving data from a caller Functions receiving data from a.
Copyright © 2000, Department of Systems and Computer Engineering, Carleton University 1 Introduction An array is a collection of identical boxes.
L what are executable/non-executable statements l out of the ones below which constructs are executable #include p=3.14; const double PI=3.14; int myfunc(int);
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 6: Functions.
1 2/2/05CS250 Introduction to Computer Science II Pointers.
1 Parameter passing Call by value The caller evaluates the actual parameters and passes copies of their values to the called function. Changes to the copies.
CPS120 Introduction to Computer Science Exam Review Lecture 18.
Array and Pointers An Introduction Unit Unit Introduction This unit covers the usage of pointers and arrays in C++
Functions Skill Area 314 Part B. Lecture Overview Functions Function Prototypes Function Definitions Local Variables Global Variables Default Parameters.
FUNCTIONS (C) KHAERONI, M.SI. OBJECTIVE After this topic, students will be able to understand basic concept of user defined function in C++ to declare.
1 This week Basics of functions Stack frames Stack vs. Heap (brief intro) Calling conventions Storage classes vs. scope Library functions Overloading.
Intro Programming in C++ Computer Science Dept Va Tech August, 2001 © Barnette ND & McQuain WD 1 Pass-by-Value - default passing mechanism except.
User-Written Functions
Lecture 7 Arrays, Dynamic Arrays & Copy Constructors “Absolute C++”
Suppose we want to print out the word MISSISSIPPI in big letters.
Pointers and Pointer-Based Strings
New Structure Recall “average.cpp” program
Chapter 6: Functions Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley.
User-Defined Functions
Call by Value Call by Reference Review
Multiple Files Revisited
Introduction to C++ Programming
Value returning Functions
Functions A function is a “pre-packaged” block of code written to perform a well-defined task Why? Code sharing and reusability Reduces errors Write and.
Functions.
6 Chapter Functions.
CS150 Introduction to Computer Science 1
CS150 Introduction to Computer Science 1
Pointers and Pointer-Based Strings
Based on slides created by Bjarne Stroustrup & Tony Gaddis
Multiple Files Revisited
CS150 Introduction to Computer Science 1
Class rational part2.
Lecture 3 More on Flow Control, More on Functions,
四時讀書樂 (春) ~ 翁森 山光照檻水繞廊,舞雩歸詠春風香。 好鳥枝頭亦朋友,落花水面皆文章。 蹉跎莫遣韶光老,人生唯有讀書好。
Presentation transcript:

Lecture 2 Functions

Functions in C++ long factorial(int n) 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. Let’s take a look at an example declaration: The declaration above has the following meaning:

Functions in C++ 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. How might our factorial function be implemented? long factorial(int n) { long result = 1, k = n; while(k > 1) { result *= k--; } return result; }

Functions in C++ #include long factorial(int); // forward declaration int main() { int x; cout “ << endl; cin >> x; cout << x << “! is “ << factorial(x) << endl; } How might we call our function from a main() function? 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

Demonstration #1 The factorial function

Argument Passing 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.

Two Function Declarations long squareIt(long x) // 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” Here is a function declared as “pass by value” 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 void main() { long y; cout “; 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

Why use 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...

Why use Pass By Reference? 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 Because you want to return two values void main() { string theTime, theTemp; getTimeAndTemp(theTime,theTemp); cout << “The time is: “ << theTime << endl; cout << “The temperature is: “ << theTemp << endl; }

Why use Pass By Reference? Because you are passing a large structure: 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) void initDataType(BIGDataType &arg1) { arg1.field1 = 0; arg1.field2 = 1; // etc., etc., assume BIGDataType has // lots of fields }

Why use Pass By Reference? bool isBusy(BIGDataType &arg1) { if (arg1.busyField = 0) return true; return false; } But be careful... 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?

Why use Pass By Reference? bool isBusy(const BIGDataType &arg1) { if (arg1.busyField = 0) return true; return false; } You can specify that a parameter cannot be modified: 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)

Scope Scope can be defined as a range of lines in a program in which any variables that are defined remain valid. Scope delimiters are the curly braces { and } Scope 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????? OK, we’ve used the “s” word a few times already today… What does it mean?

Scope void main() { int x = 0,y = 1, k = 5; { int x = 1; cout << “x is “ << x << “, y is “ << y << endl; } cout << “x is “ << x << “ and k is “ << k << endl; } Scope Delimiters may appear by themselves... 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.

Scope void main() { int x = 0,y = 1; { int x = 1, k = 5; cout << “x is “ << x << “, y is “ << y << endl; } cout << “x is “ << x << “ and k is “ << k << endl; } What is wrong here? You may only access variables that are declared in the current scope or “above”.

Scope int globalX = 0; int main() { int x = 0,y = 1,k = 5; { int x = 1; cout << “x is “ << x << “, y is “ << y << endl; globalX = 10; } cout << “x is “ << x << “ and k is “ << k << endl; cout << “globalX is “ << globalX << endl; } There is a global scope... What happens here?

Demonstration #4 Miscellaneous Scope Issues

Function Declarations vs. Definitions We’ve been somewhat lax about this... 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. long squareIt(long);// Declaration (or prototype). long squareIt(long x)// Definition { return( x * x ); }

Function Declarations and Header Files 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...

Function Declarations and Header Files // mymath.h -- header file for math functions long squareIt(long); // mymath.cpp -- implementation of math functions long squareIt(long x) { return x * x; } // main.cpp #include “mymath.h” void main() { cout >> “5 squared is “ >> squareIt(5) >> endl; }

Function Declarations and Header Files MAIN.CPP #include “MyMath.h” int main() { int x=squareIt(5); cout << x << endl; } MYMATH.CPP long squareIt(long x) { return x * x; } MYMATH.H long squareIt(long x); We start out with three files. When the compiler begins compiling MAIN.CPP, it will “include” the MYMATH.H header file…

Function Declarations and Header Files MAIN.CPP int main() { int x=squareIt(5); cout << x << endl; } MYMATH.CPP long squareIt(long x) { return x * x; } MYMATH.H long squareIt(long x); When the compiler begins compiling MAIN.CPP, the contents of MYMATH.H are actually “drawn in” to the MAIN.CPP file. The compiler sees the declaration of squareIt() from MYMATH.H and so is happy when it comes time to compile the call to squareIt() In the main() function.