Chapter 5 Functions. Introducing Functions

Similar documents
Simple C++ Programs. Engineering Problem Solving with C++, Etter/Ingber. Dev-C++ Dev-C++ Windows Friendly Exit. The C++ Programming Language

C Programming Language

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

Comp151. Definitions & Declarations

Goals for This Lecture:

Final Exam Review: VBA

C++ INTERVIEW QUESTIONS

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

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

13 Classes & Objects with Constructors/Destructors

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

SOME EXCEL FORMULAS AND FUNCTIONS

The OptQuest Engine Java and.net Developer's Guilde

Moving from C++ to VBA

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

C++FA 5.1 PRACTICE MID-TERM EXAM

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

Formatting Numbers with C++ Output Streams

Glossary of Object Oriented Terms

Expense Management. Configuration and Use of the Expense Management Module of Xpert.NET

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

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

VB.NET Programming Fundamentals

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

Basics of I/O Streams and File I/O

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

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

The University of the State of New York REGENTS HIGH SCHOOL EXAMINATION MATHEMATICS B. Thursday, January 29, :15 a.m. to 12:15 p.m.

AIMMS Function Reference - Arithmetic Functions

Ch 7-1. Object-Oriented Programming and Classes

Lecture 2 Notes: Flow of Control

Chapter 5. Selection 5-1

Computer Programming C++ Classes and Objects 15 th Lecture

6. Control Structures

C++FA 3.1 OPTIMIZING C++

TMS320C67x FastRTS Library Programmer s Reference

CSI33 Data Structures

Chapter 4 OOPS WITH C++ Sahaj Computer Solutions

Introduction to C++ Introduction to C++ Week 7 Dr Alex Martin 2013 Slide 1

JAVA - METHODS. Method definition consists of a method header and a method body. The same is shown below:

Habanero Extreme Scale Software Research Project

Passing 1D arrays to functions.

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

Class 16: Function Parameters and Polymorphism

Chapter 8 Selection 8-1

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

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

Schedule. Structures and Classes in C++ Outline. Goals for This Topic. Another Example of a Structure. What is a Structure? Classes May 12-17, 2005

Handout 1. Introduction to Java programming language. Java primitive types and operations. Reading keyboard Input using class Scanner.

Sample Questions Csci 1112 A. Bellaachia

The C Programming Language course syllabus associate level

Java Programming Fundamentals

Subtopics - Functions Function Declaration Function Arguments Return Statements and values. By Hardeep Singh

TESTING CENTER SARAS USER MANUAL

Functions and Parameter Passing

Object Oriented Software Design II

EP241 Computer Programming

Answers to Review Questions Chapter 7

Week 1: Review of Java Programming Basics

Note: Syntactically, a ; is needed at the end of a struct definition.

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

Classes and Objects in Java Constructors. In creating objects of the type Fraction, we have used statements similar to the following:

GRE Prep: Precalculus

2. Descriptive statistics in EViews

Exercise 4 Learning Python language fundamentals

Chapter 9 Delegates and Events

Chapter 2: Elements of Java

SOLVING TRIGONOMETRIC EQUATIONS

Solving Equations and Inequalities

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

COMPUTER SCIENCE 1999 (Delhi Board)

5 CLASSES CHAPTER. 5.1 Object-Oriented and Procedural Programming. 5.2 Classes and Objects 5.3 Sample Application: A Clock Class

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

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

Object-Oriented Programming

ALGEBRA 2/TRIGONOMETRY

ESPResSo Summer School 2012

Getting Started with MasteringPhysics

KITES TECHNOLOGY COURSE MODULE (C, C++, DS)

Algebra. Exponents. Absolute Value. Simplify each of the following as much as possible. 2x y x + y y. xxx 3. x x x xx x. 1. Evaluate 5 and 123

Short Notes on Dynamic Memory Allocation, Pointer and Data Structure

Appendix K Introduction to Microsoft Visual C++ 6.0

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

AP Computer Science Java Subset

Parameter Passing. Parameter Passing. Parameter Passing Modes in Fortran. Parameter Passing Modes in C

Semester 2, Unit 4: Activity 21

FX 260 Training guide. FX 260 Solar Scientific Calculator Overhead OH 260. Applicable activities

CS 141: Introduction to (Java) Programming: Exam 1 Jenny Orr Willamette University Fall 2013

CSCI 123 INTRODUCTION TO PROGRAMMING CONCEPTS IN C++

User Guide.

Data Structures. Algorithm Performance and Big O Analysis

C Compiler Targeting the Java Virtual Machine

Friday, January 29, :15 a.m. to 12:15 p.m., only

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

Conditions & Boolean Expressions

CSE373: Data Structures and Algorithms Lecture 3: Math Review; Algorithm Analysis. Linda Shapiro Winter 2015

7.7 Case Study: Calculating Depreciation

ALGEBRA 2/TRIGONOMETRY

Transcription:

Chapter 5 Functions 1 Introducing Functions A function is a collection of statements that are grouped together to perform an operation Define a function Invoke a funciton return value type method name formal parameters function header function body int max(int num1, int num2) int result; if (num1 > num2) result = num1; else result = num2; parameter list return value int z = max(x, y); actual parameters (arguments) return result; 2 1

animation Calling Functions, cont pass the value i pass the value j int main() int i = 5; int j = 2; int k = max(i, j); cout << "The maximum between " << i << " and " + j + " is " << k; return 0; int max(int num1, int num2) int result; if (num1 > num2) result = num1; else result = num2; return result; 3 Pass by Value When you invoke a function with a parameter, the value of the argument is passed to the parameter This is referred to as passby-value If the argument is a variable rather than a literal value, the value of the variable is passed to the parameter The variable is not affected, regardless of the changes made to the parameter inside the function We will examine an interesting scenario in the following example, in which the parameters are changed in the function but the arguments are not affected TestPassByValue 4 2

Pass by Value, cont The values of num1 and num2 are passed to n1 and n2 Executing swap does not affect num1 and num2 Space required for the swap function temp: n2: 2 n1: 1 Space required for the main function num2: 2 num1: 1 Space required for the main function num2: 2 num1: 1 Space required for the main function num2: 2 num1: 1 Stack is empty The main funciton is invoked The swap function is invoked The swap function is finished The main function is finished 5 Reference Variables C++ provides a special type of variable, called a reference variable, which can be used as a function parameter to reference the original variable A reference variable is an alias for another variable Any changes made through the reference variable are actually performed on the original variable To declare a reference variable, place the ampersand (&) in front of the name For example, see Listing 54 TestReferenceVariable 6 3

Pass By Reference You can use a reference variable as a parameter in a function and pass a regular variable to invoke the function The parameter becomes an alias for the original variable This is known as passby-reference When you change the value through the reference variable, the original value is actually changed TestPassByReference 7 Overloading Functions The max function that was used earlier works only with the int data type But what if you need to find which of two floating-point numbers has the maximum value? The solution is to create another function with the same name but different parameters, as shown in the following code: TestFunctionOverloading 8 4

Ambiguous Invocation Sometimes there may be two or more possible matches for an invocation of a function, but the compiler cannot determine the most specific match This is referred to as ambiguous invocation Ambiguous invocation is a compilation error 9 Ambiguous Invocation #include <iostream> using namespace std; int maxnumber(int num1, double num2) if (num1 > num2) return num1; else return num2; double maxnumber(double num1, int num2) if (num1 > num2) return num1; else return num2; int main() cout << maxnumber(1, 2) << endl; return 0; 10 5

Function Prototypes Before a function is called, it must be declared first One way to ensure it is to place the declaration before all function calls Another way to approach it is to declare a function prototype before the function is called A function prototype is a function declaration without implementation The implementation can be given later in the program TestFunctionPrototype 11 Default Arguments C++ allows you to declare functions with default argument values The default values are passed to the parameters when a function is invoked without the arguments DefaultArgumentDemo 12 6

Scope of Local Variables, cont A variable declared in the initial action part of a for loop header has its scope in the entire loop But a variable declared inside a for loop body has its scope limited in the loop body from its declaration and to the end of the block that contains the variable The scope of i The scope of j void method1() for (int i = 1; i < 10; i++) int j; 13 Scope of Local Variables, cont It is fine to declare i in two non-nesting blocks void function1() int x = 1; int y = 1; for (int i = 1; i < 10; i++) x += i; for (int i = 1; i < 10; i++) y += i; It is illegal to declare i in two nesting blocks void function2() int i = 1; int sum = 0; for (int i = 1; i < 10; i++) sum += i; cout << i << endl; cout << sum << endl; 14 7

Global Variables C++ also allows you to use global variables They are declared outside all functions and are accessible to all functions in its scope Local variables do not have default values, but global variables are defaulted to zero VariableScopeDemo 15 Unary Scope Resolution If a local variable name is the same as a global variable name, you can access the global variable using ::globalvariable The :: operator is known as the unary scope resolution For example, the following code: #include <iostream> using namespace std; int v1 = 10; int main() int v1 = 5; cout << "local variable v1 is " << v1 << endl; cout << "global variable v1 is " << ::v1 << endl; return 0; 16 8

Static Local Variables After a function completes its execution, all its local variables are destroyed Sometimes, it is desirable to retain the value stored in local variables so that they can be used in the next call C++ allows you to declare static local variables Static local variables are permanently allocated in the memory for the lifetime of the program To declare a static variable, use the keyword static StaticVariableDemo 17 Function Abstraction You can think of the Function body as a black box that contains the detailed implementation for the Function Optional arguments for Input Optional return value Method Signature Method body Black Box 18 9

Benefits of Functions Write a Function once and reuse it anywhere Information hiding Hide the implementation from the user Reduce complexity 19 Math Functions Function Description Example abs(x) Returns the absolute value of the argument abs(-2) is 2 ceil(x) x is rounded up to its nearest integer and ceil(21) is 3 returns this integer ceil(-21) is -2 floor(x) x is rounded down to its nearest integer and floor(21) is 2 returns this integer floor(-21) is -3 exp(x) Returns the exponential function of x exp(1) is 271828 pow(x, y) Returns a raised to power b (x y ) pow(20, 3) is 8 log(x) Returns the natural logarithm of x log(271828) is 10 log10(x) Returns the base-10 logarithm of x log10(100) is 1 sqrt(x) Returns the square root of x sqrt(40) is 2 sin(x) Returns the sine of x x represents an angle sin(314159 / 2) is 1 in radians sin(314159) is 0 cos(x) Returns the cosine of x x represents an cos(314159 / 2) is 0 angle in radians cos(314159) is -1 tan(x) Returns the tangent of x x represents an tan(314159 / 4) is 1 angle in radians tan(00) is 0 fmod(x, y) Returns the remainder of x/y as double fmod(24, 13) is 11 20 10

Inline Functions Implementing a program using functions makes the program easy to read and easy to maintain, but function calls involve runtime overhead (ie, pushing arguments and CPU registers into the stack and transferring control to and from a function) C++ provides inline functions to avoid function calls Inline functions are not called; rather, the compiler copies the function code in line at the point of each invocation To specify an inline function, precede the function declaration with the inline keyword, as shown in Listing 518 InlineDemo InlineDemo1 21 Short Functions Not for long Functions Compiler Decision Inline functions are desirable for short functions, but not suitable for long functions that are called in multiple places in a program, because long inline functions will dramatically increase the executable code size when it is copied in multiple places For this reason, C++ allows the compilers to ignore the inline keyword if the function is too long So, the inline keyword is merely a request to the compiler, and it is up for the compiler to make the decision whether to honor it or ignore it 22 11