32
Functions

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

Embed Size (px)

DESCRIPTION

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);

Citation preview

Page 1: 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

Functions

Page 2: 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

Predefined Functions

Page 3: 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

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 functionthe_root = sqrt(9.0);

Page 4: 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

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 <cmath>

Page 5: 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

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 castingint a = 9, b = 2;double c = double(a/b);

Page 6: 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

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<int>(b);

• dynamic casting (later – inheritance)

Page 7: 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

• 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

Page 8: 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

Programmer-Defined Functions

Page 9: 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

• 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

Page 10: 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

• 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

Page 11: 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 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

Page 12: 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

• 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 formint add1(int);

– function definition - explains what the function does• function header• function body

Programmer-Defined Functions

Page 13: 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

double CircleArea (double r) {

const double PI = 3.1415; return PI * r * r;

}

Function Definition

function bodyreturn statement

parameterreturn type function name

function header

Page 14: 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

• 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

Page 15: 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

#include <iostream>double CircleArea(double r); // computes circle area

// manage circle computationint main() { cout << "Enter radius: "; float MyRadius; // circle radius cin >> MyRadius; double Area = CircleArea(MyRadius); cout << "Circle has area " << Area;}

// computes area of radius r circledouble CircleArea(double r) { const double PI = 3.1415; return PI * r * r;}

Ch 6/ Foil 15What are the names of the elements in gray boxes?

Page 16: 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

• 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

Page 17: 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

• 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

Page 18: 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

• 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

Page 19: 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

• 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...bint sum(int a, int b) {

int total = 0; // this is a local variablefor (int i = a; i <= b; ++i) {

total += i;}return total;

}

Local Variables

Page 20: 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

• 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 declaredconst 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

Page 21: 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

Simple Programs

• single file structure– include statements– using statements– function prototypes– function definitions

Page 22: 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

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

Page 23: 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

Programmer-Defined Functions II

Void functions, call-by-reference

Page 24: 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

• 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

Page 25: 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

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

Page 26: 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

Pointers

• A pointer stores the address of some other object

• The address-of (&) operator obtains the address of an objectint N = 26;int *pN = &N; // get the address

Page 27: 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

Implementing Pointers

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

Page 28: 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

• 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

Page 29: 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

• Definitionvoid 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

Page 30: 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 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.)

Page 31: 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

• Functions that need to return more than one value usually use call-by-referenceprototype: 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 STYLEcall: first_num = get_numbers(second_num); // BAD STYLE

Call-by-Reference (Cont.)

Page 32: 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

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