Functions. Predefined Functions C++ comes with libraries of code that can be reused in your programs. The code comes in the form of predefined functions.

Slides:



Advertisements
Similar presentations
Chapter 7: User-Defined Functions II
Advertisements

Functions  Programmer-Defined Functions  Local Variables in Functions  Overloading Function Names  void Functions,  Call-By-Reference Parameters in.
Chapter 5 Functions.
Chapter 3 Assignment and Interactive Input. 2 Objectives You should be able to describe: Assignment Operators Mathematical Library Functions Interactive.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 5 - Functions Outline 5.1Introduction 5.2Program.
J. P. Cohoon and J. W. Davidson © 1999 McGraw-Hill, Inc. Programmer-defined functions Development of simple functions using value parameters.
CPSC230 Computers & Programming I Lecture Notes 20 Function 5 Dr. Ming Zhang.
Chapter 6. 2 Objectives You should be able to describe: Function and Parameter Declarations Returning a Single Value Pass by Reference Variable Scope.
CS 201 Functions Debzani Deb.
 2003 Prentice Hall, Inc. All rights reserved. 1 Functions Modules: functions and classes Programs use new and “prepackaged” modules –New: programmer-defined.
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.
Basic Elements of C++ Chapter 2.
C++ Functions. 2 Agenda What is a function? What is a function? Types of C++ functions: Types of C++ functions: Standard functions Standard functions.
Chapter 6: Functions.
Chapter 4:Functions| SCP1103 Programming Technique C | Jumail, FSKSM, UTM, 2005 | Last Updated: September 2005 Slide 1 Functions Lecture 4 by Jumail Bin.
Chapter 4 Procedural Abstraction and Functions That Return a Value.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 19 Clicker Questions November 3, 2009.
Modular Programming Chapter Value and Reference Parameters t Function declaration: void computesumave(float num1, float num2, float& sum, float&
Operator Precedence First the contents of all parentheses are evaluated beginning with the innermost set of parenthesis. Second all multiplications, divisions,
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. C How To Program - 4th edition Deitels Class 05 University.
1 Chapter 8 Scope, Lifetime, and More on Functions Dale/Weems/Headington.
Chapter 6: User-Defined Functions
Project 1 Due Date: September 25 th Quiz 4 is due September 28 th Quiz 5 is due October2th 1.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Iterative Constructs Review l What are named constants? Why are they needed? l What is a block? What is special about declaring a variable inside a block?
Defining and Converting Data Copyright Kip Irvine, 2003 Last Update: 11/4/2003.
C++ Functions. Objectives 1. Be able to implement C++ functions 2. Be able to share data among functions 2.
Chapter 4 Procedural Abstraction and Functions That Return a Value.
Programming in C++ Language ( ) Lecture 5: Functions-Part1 Dr. Lubna Badri.
CPS120: Introduction to Computer Science Functions.
ADTs and C++ Classes Classes and Members Constructors The header file and the implementation file Classes and Parameters Operator Overloading.
Chapter 4: Subprograms Functions for Problem Solving Mr. Dave Clausen La Cañada High School.
CPS120: Introduction to Computer Science Lecture 14 Functions.
L function n predefined, programmer-defined l arguments, (formal) parameters l return value l function call, function invocation l function definition.
Liang, Introduction to C++ Programming, (c) 2010 Pearson Education, Inc. All rights reserved Chapter 6 Advanced Function Features.
1 Announcements Note from admins: Edit.cshrc.solaris instead of.tcshrc Note from admins: Do not use delta.ece.
C++ Programming Lecture 9 Functions – Part I By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department.
1 COMS 261 Computer Science I Title: Functions Date: October 12, 2005 Lecture Number: 17.
Starting Out with C++ Early Objects ~~ 7 th Edition by Tony Gaddis, Judy Walters, Godfrey Muganda Modified for CMPS 1044 Midwestern State University 6-1.
 2003 Prentice Hall, Inc. All rights reserved. 1 IS 0020 Program Design and Software Tools Preprocessor Midterm Review Lecture 7 Feb 17, 2004.
Chapter 3 Functions. 2 Overview u 3.2 Using C++ functions  Passing arguments  Header files & libraries u Writing C++ functions  Prototype  Definition.
Functions Illustration of: Pass by value, reference Scope Allocation Reference: See your CS115/215 textbook.
L what are predefined functions? l what is? n function name n argument(s) n return value n function call n function invocation n nested function call l.
Function User defined function is a code segment (block) that perform an specific action. Function Definition: Function Definition: Return_DT F_name (
Functions Math library functions Function definition Function invocation Argument passing Scope of an variable Programming 1 DCT 1033.
1 MORE ON MODULAR DESIGN: MODULE COMMUNICATIONS. 2 WHEN A FUNCTION IS INVOKED, MEMORY IS ALLOCATED LOCALLY FOR THE FORMAL PARAMETERS AND THE VALUE OF.
Recap……Last Time [Variables, Data Types and Constants]
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);
EEL 3801 C++ as an Enhancement of C. EEL 3801 – Lotzi Bölöni Comments  Can be done with // at the start of the commented line.  The end-of-line terminates.
 2000 Prentice Hall, Inc. All rights reserved Introduction Divide and conquer –Construct a program from smaller pieces or components –Each piece.
Functions in C++ Top Down Design with Functions. Top-down Design Big picture first broken down into smaller pieces.
Programming Fundamentals Enumerations and Functions.
Functions Skill Area 314 Part B. Lecture Overview Functions Function Prototypes Function Definitions Local Variables Global Variables Default Parameters.
Building Programs from Existing Information Solutions for programs often can be developed from previously solved problems. Data requirements and solution.
Functions Procedural Abstraction Flow of Control INFSY 307 Spring 2003 Lecture 4.
 2000 Prentice Hall, Inc. All rights reserved Program Components in C++ Function definitions –Only written once –These statements are hidden from.
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.
Chapter Topics The Basics of a C++ Program Data Types
-Neelima Singh PGT(CS) KV Sec-3 Rohini
Introduction to C++ Systems Programming.
Predefined Functions Revisited
Basic Elements of C++.
FUNCTIONS IN C++.
User-Defined Functions
Basic Elements of C++ Chapter 2.
Multiple Files Revisited
Multiple Files Revisited
Predefined Functions Revisited
Presentation transcript:

Functions

Predefined Functions

C++ comes with libraries of code that can be reused in your programs. The code comes in the form of predefined functions function name - identifier distinguishing the function from others; Example: square root function sqrt argument - the value function starts out with; function may have more than one argument; an argument is an expression (thus, can be just a simple constant or variable); return value - value computed by the function the_root = sqrt(9.0);

Predefined Functions function call (function invocation) - expression consisting of function name followed by arguments in parentheses Function accepts parameters of certain type and returns value of certain type; sqrt accepts and returns double To use a function need to specify include directive: #include

Type Changing Functions Is there a problem with this code? int a=9, b=2; double c=a/b ; C++ provides functions for explicit conversions between types: – function double converts to type double: int a = 9, b = 2; double c = double(a)/b ; Explicit type conversion is called type casting warning: wrong application of casting int a = 9, b = 2; double c = double(a/b) ;

Casting Types functional and c-like casting short a = 2000; int b; b = (int) a; // c-like cast b = int (a); // functional static casting (no run time checks are performed) int a; double b = ; a = static_cast (b); dynamic casting (later – inheritance)

what are predefined functions? what is – function name – argument(s) – return value – function call – function invocation what is the type of arguments and the type of return value and why are they important? what is include directive and how is it related to predefined functions? what are type changing functions and why are they needed? what is type casting? Predefined Functions Revisited

Programmer-Defined Functions

Functions are named portions of code Two types of functions: – predefined - provided in libraries for the benefit of all programmers – programmer-defined - written by programmer To carry out its task the function accepts arguments To use a function the programmer writes the function name and a list of arguments for the function to use. This is called function call (or function invocation) Functions

Every function returns a result in a return value Function call can be used in any place an expression or statement is used – if a function is used as an expression - the function evaluates to its return value – if a function is used as a statement - the return value is ignored Arguments and return value of a function are of specified type Functions

Function Invocation cout << add1(4+5) << endl; Invocation is part of a larger expression. To process the invocation, the function that contains the insertion statement is suspended and add1() does its job. The insertion statement is then completed using the value supplied by add1(). argument - can be an expression

Programmer defined function cannot know what arguments will be passed to it; it uses (formal) parameters Formal parameters are given values of arguments in the sequence they are listed Programmer-defined function needs to be described by the programmer The description consists of two parts – function prototype - quickly introduces the function return_value function_name (type parameter_name,…,); example: int add1(int i); parameter names are optional but sometimes desirable for clarity abbreviated form int add1(int); – function definition - explains what the function does function header function body Programmer-Defined Functions

double CircleArea (double r) { const double PI = ; return PI * r * r; } Function Definition function body return statement parameter return type function name function header

return-statement specifies what value the function returns: return expression; Expression is evaluated, converted to the type specified in function head (watch out!) and function terminates return-statement is optional. If a function does not have a return-statement it terminates when the last statement is executed. The returned value is unspecified Technically a function can have multiple return statements; but it is advisable to have just one at the end of the function - such a function is easier to read Return Statement

#include double CircleArea(double r); // computes circle area // manage circle computation int main() { cout << "Enter radius: "; float MyRadius; // circle radius cin >> MyRadius; double Area = CircleArea(MyRadius); cout << "Circle has area " << Area; } // computes area of radius r circle double CircleArea(double r) { const double PI = ; return PI * r * r; } Ch 6/ Foil 15 What are the names of the elements in gray boxes?

Before calling a function it needs to be declared: – function prototype and function definition declares the function Unlike variables the function declarations and function prototypes should be put outside any other function – no nested functions in C++ standard (even though g++ supports it) Technically you do not need function prototypes - just put all the function definitions first – this would result in a program structure where functions implementing details go first and more abstract functions follow - these programs are hard to read and understand – appropriate program style - put function prototypes first, then main() then other function with the increasing level of detail Declaring a Function: Style

Commenting functions – treat a function prototype as a variable definition - append a short description of the function – precede a function definition with at least one line of comments explaining what the function is doing and what the parameters are for Declaring a Function, Style

A programmer that uses a certain function needs to know what the function does but does not need to know how the function does it Anybody knows how sqrt() determines square root? Such treatment of a function is called black box principle If a function is well designed a programmer can use it as a black box Designing functions to be used as black boxes is called information hiding; another name for it is procedural abstraction - the programmer abstracts away the details of the code in the function’s body Such approach decreases the complexity of programming Function as Black Box

Variable that is declared inside a function is local. It is cannot be used outside of the function – the scope of such variable is from declaration till function end Parameters are also local variables Local variables of two different functions are different even if they have the same name Note that variables declared in main() are local to main() as well // computes sum of integers in a...b int sum(int a, int b) { int total = 0; // this is a local variable for (int i = a; i <= b; ++i) { total += i; } return total; } Local Variables

The same constants may be used in multiple functions If a constant is declared outside any function it is called global and it can be used (its scope is) anywhere in the program from the place it is declared const double PI = ; const double TAX_RATE = 0.05; // 5% sales tax Similarly one can declare global variables. Global variables can be used and modified in any function of the program: int errorcode = 0; – using global variables makes your program hard to understand and debug and should be avoided Global constant and variable declarations should be grouped and placed at the beginning of your program Global Constants and Variables

Simple Programs single file structure – include statements – using statements – function prototypes – function definitions

Call-by-Value Formal parameters are local variables of the function When the function is called the values of the arguments are evaluated and assigned to respective parameters As any local variable, the value of a parameter can be changed in a function This change does not affect the values of the original arguments Such mechanism of parameter passing is called call-by-value

Programmer-Defined Functions II Void functions, call-by-reference

Frequently void functions are output functions void show_results(double fard, double celd){ cout << fard << “ degrees Fahrenheit is equivalent to\n” << celd << “ degrees Celsius.\n”; return; // not necessary } Void Function Example

Reference Variables Address operator & in variable declaration type &reference_variable = variable_of_type; Reference variable – No real variables – Proxy or alias for another variable – Must be initialized during declaration (with lvalue - a thing that can be on the left side of an assignment, i.e. it can take a value) Example: int x = 5; // variable int &rx = x; // reference to x x = 6; // x==6 and rx==6 rx++; // x==7 and rx==7 Operations on reference variables affect the referenced variables

Reference Variables Reference parameters – Allow implicit call-by-reference semantics – No pointers necessary – Caller writes down call with normal syntax – Disadvantage: syntax of call does not show semantics Example: #include void increment(int& x) { x++; } void main() { int x = 5; increment( x ); cout << "x=" << x << "\n"; // x==6 }

Reference Variables Returning references is also possible – Function returns a variable (lvalue) not a value int global = 0; // global variable int& func() { return global; // returns reference to global } int main() { int x; x = func() + 1; // x = global + 1; func() = x; // global = x; } NOTE: returning references to local variables is forbidden int& func() { int x = 0; int& rx = x; return rx; // forbidden }

References vs Pointers A reference is an alias for some existing object Physically, the reference stores the address of the object it references In the following example, when we assign a value to rN, we automatically modify N: int N = 25; int & rN = N; rN = 36; cout << N; // "36" displayed

Pointers A pointer stores the address of some other object The address-of (&) operator obtains the address of an object int N = 26; int *pN = &N; // get the address

Implementing Pointers pN N 29A6 26 (Address 29A6) pN points to N because pN contains N's address

What was call-by-value? call-by-reference allows the functions to modify the arguments To distinguish call-by-reference, ampersand (&) precedes parameter declaration both in function head and in function prototype! prototype, extened form: void get_intput(double &fard); prototype, abbreviated form: void get_intput(double &); Call-by-Reference

Definition void get_intput(double &fard){ cout << “I will convert Fahrenheit Temperature ” << “to Celsius.\n” << “Enter temperature in Fahrenheit: “; << “ degrees Celsius.\n”; cin >> fard; } Mixing calls of parameters is allowed: myfunc(int&,double,int&); Call-by-Reference

Function invocations for call-by-reference and call-by- value look the same: double f_temp; get_input(f_temp); Passing expressions in call-by-reference is not allowed! get_input(23.0); // WRONG! In call-by-reference the function operates on the memory location of the argument Call-by-Reference (Cont.)

Functions that need to return more than one value usually use call-by-reference prototype: void get_numbers(int& input1, int& input2); call: get_numbers(first_num, second_num); Passing one similar value as return and the other as parameter is bad style: prototype: int get_numbers(int& input2); // BAD STYLE call: first_num = get_numbers(second_num); // BAD STYLE Call-by-Reference (Cont.)

Inlining Reserved word inline: inline return_type function_name( parameter_list ) { function_body} – Compiler tries to optimize function calls – Instead of a function call the body of the whole function is inserted Faster calls, but larger programs – Further optimizations possible (e.g. for calls with constant parameters) – Not possible for recursive functions – Function body must be implemented in the header file (.H or.hh)!!! Differences to pre-processor macros (#define): – Macros are expanded as normal text No type checking, often mysterious syntax errors

Default Parameters Function parameters may contain default values Will be used when the actual parameter in a call is missing – Only at the end of the parameter list, no gaps allowed Example: void print(char* string, int nl = 1); print( "Test", 0 ); print( "Test" ); // is equal to print( "Test", 1 ) print(); // wrong, char* parameter is missing Caution: overloading and default parameters may generate ambiguities void print(char* string); void print(char* string, int nl = 1); print( "Test" ); // which function ??????????