Download presentation
Presentation is loading. Please wait.
Published byElizabeth Heather Russell Modified over 9 years ago
1
Functions
2
Predefined Functions
3
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);
4
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
5
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) ;
6
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 = 5234.6345; a = static_cast (b); dynamic casting (later – inheritance)
7
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
8
Programmer-Defined Functions
9
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
10
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
11
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
12
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
13
double CircleArea (double r) { const double PI = 3.1415; return PI * r * r; } Function Definition function body return statement parameter return type function name function header
14
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
15
#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 = 3.1415; return PI * r * r; } Ch 6/ Foil 15 What are the names of the elements in gray boxes?
16
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
17
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
18
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
19
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
20
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 = 3.14159; 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
21
Simple Programs single file structure – include statements – using statements – function prototypes – function definitions
22
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
23
Programmer-Defined Functions II Void functions, call-by-reference
24
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
25
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
26
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 }
27
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 }
28
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
29
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
30
Implementing Pointers pN N 29A6 26 (Address 29A6) pN points to N because pN contains N's address
31
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
32
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
33
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.)
34
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.)
35
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
36
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 ??????????
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.