functions skill area 314 part b. lecture overview functions function prototypes function...

43
Functions Skill Area 314 Part B Materials Prepared by Dhimas Ruswanto, BMm

Upload: blanche-reed

Post on 20-Jan-2018

222 views

Category:

Documents


0 download

DESCRIPTION

What is a FUNCTION? A function is a group of statements that is executed when it is called from some point of the program.

TRANSCRIPT

Page 1: Functions Skill Area 314 Part B. Lecture Overview Functions Function Prototypes Function Definitions…

FunctionsSkill Area 314 Part

BMaterials Prepared by Dhimas Ruswanto, BMm

Page 2: Functions Skill Area 314 Part B. Lecture Overview Functions Function Prototypes Function Definitions…

Lecture Overview• Functions• Function Prototypes• Function Definitions• Local Variables• Global Variables• Default Parameters• Overloaded Functions• Passing by Value• Passing by Reference• Inline Functions• Recursion

Page 3: Functions Skill Area 314 Part B. Lecture Overview Functions Function Prototypes Function Definitions…

What is a FUNCTION?

• A function is a group of statements that is executed when it is called from some point of the program.

Page 4: Functions Skill Area 314 Part B. Lecture Overview Functions Function Prototypes Function Definitions…

FUNCTION PROTOTYPE

FUNCTION DEFINITION

Page 5: Functions Skill Area 314 Part B. Lecture Overview Functions Function Prototypes Function Definitions…

Declaration and Definition• Using functions in your program requires

that you first declare the function and that you then define the function.

• The declaration tells the compiler the name, return type, and parameters of the function.

• The definition tells the compiler how the function works. No function can be called from any other function that hasn't first been declared.

• The declaration of a function is called its PROTOTYPE.

Page 6: Functions Skill Area 314 Part B. Lecture Overview Functions Function Prototypes Function Definitions…

Function Prototype• Many of the built-in functions you use will have

their function prototypes already written in the files you include in your program by using #include. For functions you write yourself, you must include the prototype.

• The function prototype is a statement, which means it ends with a semicolon. It consists of the function's return type, name, and parameter list.

• The parameter list is a list of all the parameters and their types, separated by commas.

int findArea (int length, int width);

return type

name

parameters

Parameter type

Parameter name

semicolon

Page 7: Functions Skill Area 314 Part B. Lecture Overview Functions Function Prototypes Function Definitions…

• Prototype that looks like this is perfectly legal (without parameter name):

int findArea (int, int);

Function Prototype

• Although this is legal, it is not a good idea. • Adding parameter names makes your prototype

clearer. • The same function with named parameters might

be int findArea (int height, int width);

Page 8: Functions Skill Area 314 Part B. Lecture Overview Functions Function Prototypes Function Definitions…

Function Definition• The definition of a function consists of the function

header and its body. • The header is exactly like the function prototype,

except that the parameters must be named, and there is no terminating semicolon.

• The body of the function is a set of statements enclosed in braces

return_type function_name ( [type parameterName]...) {

statements; }

int area ( int height, int width) {

return height* width;}

Page 9: Functions Skill Area 314 Part B. Lecture Overview Functions Function Prototypes Function Definitions…

Function Definition

• return type is the data type specifier of the data returned by the function.

• function_name is the identifier by which it will be possible to call the function.

• parameters (as many as needed): Each parameter consists of a data type specifier followed by an identifier, like any regular variable declaration (for example: int x) and which acts within the function as a regular local variable. They allow to pass arguments to the function when it is called. The different parameters are separated by commas.

• statements is the function's body. It is a block of statements surrounded by braces { }.

return_type function_name ( [type parameterName]...) {

statements; }

Page 10: Functions Skill Area 314 Part B. Lecture Overview Functions Function Prototypes Function Definitions…

NOTE

• The function prototype and the function definition must agree exactly about the return type, the name, and the parameter list.

• If they do not agree, you will get a compile-time error.

Page 11: Functions Skill Area 314 Part B. Lecture Overview Functions Function Prototypes Function Definitions…

Functions#include <iostream>using namespace std;int add (int a, int b); //function prototypeint main (){ int x=1, y=3; cout << "x + y= "<< add(x,y); //calling function add() system ("pause"); return 0;} //function definitionint add (int a, int b){ return a+b;}

Page 12: Functions Skill Area 314 Part B. Lecture Overview Functions Function Prototypes Function Definitions…

NOTE

• If you try to placing the a function before the main() function without declared the function first, you will have compile-time error

Page 13: Functions Skill Area 314 Part B. Lecture Overview Functions Function Prototypes Function Definitions…

Functions with no Type (VOID)

• We do not need it to return any value. • We use the void type specifier for the

function. • This is a special specifier that

indicates absence of type.• It is called PROCEDURE

//function definitionvoid printmessage () {

cout << “I’m a function!”;}

void printmessage() ; //function prototype

Page 14: Functions Skill Area 314 Part B. Lecture Overview Functions Function Prototypes Function Definitions…

Functions with no Type (VOID)

// void function example #include <iostream> using namespace std; void printmessage (); //function prototypeint main () {

printmessage (); return 0;

}//function definitionvoid printmessage () {

cout << "I'm a function!"; }

Page 15: Functions Skill Area 314 Part B. Lecture Overview Functions Function Prototypes Function Definitions…

Functions with no Type (VOID)

// void function example #include <iostream> using namespace std; void subtract(int a, int b); //function prototypeint main () {

int x=7, y=2;subtract (x,y); return 0;

}//function definitionvoid subtract(int a, int b) {

int c;c=a-b; cout << c;

}

Page 16: Functions Skill Area 314 Part B. Lecture Overview Functions Function Prototypes Function Definitions…

LOCAL VARIABLESGLOBAL VARIABLES

Page 17: Functions Skill Area 314 Part B. Lecture Overview Functions Function Prototypes Function Definitions…

Scope of Variables• The scope of variables declared within a function

or any other inner block is only their own function or their own block and cannot be used outside of them.

• Local variables are defined like any other variables.

• The parameters passed in to the function are also considered local variables and can be used exactly as if they had been defined within the body of the function.

• Variables defined outside of any function have global scope and thus are available from any function in the program, including main().

• In order to declare global variables you simply have to declare the variable outside any function or block; that means, directly in the body of the program.

Page 18: Functions Skill Area 314 Part B. Lecture Overview Functions Function Prototypes Function Definitions…

Scope of Variables#include <iostream>using namespace std;int multiply (int a, int b);int x=5, y=6; //GLOBAL variablesint main(){

int i=7,j=9; //LOCAL variablescout << multiply(i,j) << endl;cout<< multiply(x,y); return 0;

}int multiply (int a, int b) {

int z; //LOCAL variablesz=a*b;return z;

}

Page 19: Functions Skill Area 314 Part B. Lecture Overview Functions Function Prototypes Function Definitions…

DEFAULT PARAMETERS

Page 20: Functions Skill Area 314 Part B. Lecture Overview Functions Function Prototypes Function Definitions…

DEFAULT Parameters• When declaring a function we can specify a

default value for each of the last parameters. • This value will be used if the corresponding

argument is left blank when calling to the function.

• To do that, we simply have to use the assignment operator and a value for the arguments in the function declaration.

• If a value for that parameter is not passed when the function is called, the default value is used, but if a value is specified this default value is ignored and the passed value is used instead. 

Page 21: Functions Skill Area 314 Part B. Lecture Overview Functions Function Prototypes Function Definitions…

DEFAULT Parameters

• For every parameter you declare in a function prototype and definition, the calling function must pass in a value.

• The value passed in must be of the declared

type. •  A default value is a value to use if none is

supplied

int findArea (int height, int width);

int findArea (int height = 50, int width=75);

Page 22: Functions Skill Area 314 Part B. Lecture Overview Functions Function Prototypes Function Definitions…

DEFAULT Parameters• If the function prototype looks like

• You can assign a default value to Param2 only if you have assigned a default value to Param3.

• You can assign a default value to Param1 only if you've assigned default values to both Param2 and Param3

int myFunction (int Param1, int Param2, int Param3);

Page 23: Functions Skill Area 314 Part B. Lecture Overview Functions Function Prototypes Function Definitions…

DEFAULT Parameter#include <iostream>using namespace std;int divide (int a, int b=2); //function prototypeint main (){ cout << divide (12); cout << endl; cout << divide (20,4); return 0;}//function definitionint divide (int a, int b){ int r; r=a/b; return (r);}

Page 24: Functions Skill Area 314 Part B. Lecture Overview Functions Function Prototypes Function Definitions…

DEFAULT Parameter#include <iostream>using namespace std;int AreaCube(int length, int width = 25, int height = 1); int main() { int length = 100;

int width = 50; int height = 2;

int area; area = AreaCube(length, width, height);

cout << "First area equals: " << area << "\n"; area = AreaCube(length, width); cout << "Second time area equals: " << area << "\n"; area = AreaCube(length);

cout << "Third time area equals: " << area << "\n"; return 0;

} AreaCube(int length, int width, int height) {

return (length * width * height); }

Page 25: Functions Skill Area 314 Part B. Lecture Overview Functions Function Prototypes Function Definitions…

OVERLOADED FUNCTIONS

Page 26: Functions Skill Area 314 Part B. Lecture Overview Functions Function Prototypes Function Definitions…

OVERLAODED Functions• In C++ two different functions can have the

same name if their parameter types or number are different.

• That means that you can give the same name to more than one function if they have either a different number of parameters or different types in their parameters.

• The functions must differ in their parameter list, with a different type of parameter, a different number of parameters, or both

• Function overloading is also called function polymorphism. Poly means many, and morph means form: a polymorphic function is many-formed.

Page 27: Functions Skill Area 314 Part B. Lecture Overview Functions Function Prototypes Function Definitions…

OVERLOADED Functions#include <iostream>using namespace std;int operate (int a, int b);float operate (float a, float b)int main (){ int x=5,y=2; float n=5.0,m=2.0; cout << operate (x,y); cout << "\n"; cout << operate (n,m); cout << "\n"; return 0;}int operate (int a, int b){ return (a*b);}float operate (float a, float b){ return (a/b);}

Page 28: Functions Skill Area 314 Part B. Lecture Overview Functions Function Prototypes Function Definitions…

ARGUMENTS PASSED BY VALUE AND BY REFERENCE

Page 29: Functions Skill Area 314 Part B. Lecture Overview Functions Function Prototypes Function Definitions…

Passing by VALUE

• What we did in this case was to call to function addition passing the values of x and y, i.e. 5 and 3 respectively, but not the variables x and y themselves.

int x=5, y=3, z;z = addition ( x , y );

• This way, when the function addition is called, the value of its local variables a and b become 5 and 3 respectively, but any modification to either a or b within the function addition will not have any effect in the values of x and y outside it, because variables x and y were not themselves passed to the function, but only copies of their values at the moment the function was called.

Page 30: Functions Skill Area 314 Part B. Lecture Overview Functions Function Prototypes Function Definitions…

Passing by REFERENCE• There might be some cases where you need to

manipulate from inside a function the value of an external variable. For that purpose we can use arguments passed by reference.

• The first thing that should call your attention is that in the declaration of function the type of each parameter was followed by an ampersand sign (&).

• This ampersand is what specifies that their corresponding arguments are to be passed by reference instead of by value.

• When a variable is passed by reference we are not passing a copy of its value, but we are somehow passing the variable itself to the function and any modification that we do to the local variables will have an effect in their counterpart variables passed as arguments in the call to the function.

Page 31: Functions Skill Area 314 Part B. Lecture Overview Functions Function Prototypes Function Definitions…

Passing by REFERENCE

• To explain it in another way, we associate a, b and c with the arguments passed on the function call (x, y and z) and any change that we do on a within the function will affect the value of x outside it. Any change that we do on b will affect y, and the same with c and z. 

• That is why our program's output, that shows the values stored in x, y and z after the call to duplicate, shows the values of all the three variables of main doubled.

• Without the ampersand signs (&), we would have not passed the variables by reference, but a copy of their values instead, and therefore, the output on screen of our program would have been the values of x, y and z without having been modified.

• Passing by reference is also an effective way to allow a function to return more than one value

Page 32: Functions Skill Area 314 Part B. Lecture Overview Functions Function Prototypes Function Definitions…

Passing by REFERENCE//with ampersand sign (&)#include <iostream>using namespace std;void operate(int& a);int main (){

int x=3;operate(x);cout << x; return 0;

}void operate (int& a){

a=2;}---------------------------------Output: 2

//without ampersand sign (&)#include <iostream>using namespace std;void operate(int a);int main (){

int x=3;operate(x);cout << x; return 0;

}void operate (int a){

a=2;}---------------------------------Output: 3

Page 33: Functions Skill Area 314 Part B. Lecture Overview Functions Function Prototypes Function Definitions…

Passing by REFERENCE// more than one returning value#include <iostream>using namespace std;void prevnext (int x, int& prev, int& next);int main (){ int x=100, y, z; prevnext (x, y, z); cout << "Previous=" << y << ", Next=" << z; return 0;}void prevnext (int x, int& prev, int& next){ prev = x-1; next = x+1;}

Page 34: Functions Skill Area 314 Part B. Lecture Overview Functions Function Prototypes Function Definitions…

INLINE FUNCTIONS

Page 35: Functions Skill Area 314 Part B. Lecture Overview Functions Function Prototypes Function Definitions…

What is INLINE functions?

• The inline functions are a C++ enhancement designed to speed up programs.

• The coding of normal functions and inline functions is similar except that inline functions definitions start with the keyword inline.

• The distinction between normal functions and inline functions is the different compilation process.

Page 36: Functions Skill Area 314 Part B. Lecture Overview Functions Function Prototypes Function Definitions…

Reason for the need of Inline Function

• Normally, a function call transfers the control from the calling program to the function and after the execution of the program returns the control back to the calling program after the function call.

• These concepts of function save program space and memory space and are used because the function is stored only in one place and is only executed when it is called.

• This execution may be time consuming since the registers and other processes must be saved before the function gets called.

• The extra time needed and the process of saving is valid for larger functions. If the function is short, the programmer may wish to place the code of the function in the calling program in order for it to be executed.

• This type of function is best handled by the inline function.

Page 37: Functions Skill Area 314 Part B. Lecture Overview Functions Function Prototypes Function Definitions…

What happens when an inline function is written?

• The inline function takes the format as a normal function but when it is compiled it is compiled as inline code.

• The function is placed separately as inline function, thus adding readability to the source program.

• When the program is compiled, the code present in function body is replaced in the place of function call.

Page 38: Functions Skill Area 314 Part B. Lecture Overview Functions Function Prototypes Function Definitions…

INLINE Functions

• The format for its declaration is:

inline type name ( arguments ... ) {

instructions ... }

Page 39: Functions Skill Area 314 Part B. Lecture Overview Functions Function Prototypes Function Definitions…

INLINE Functions #include <iostream>using namespace std; int exforsys(int);int main( ){ int x; cout << "n Enter the Input Value: "; cin>>x; cout << "n The Output is: " << exforsys(x); return 0;} inline int exforsys (int x1) //INLINE Function{ return 5*x1;}

Page 40: Functions Skill Area 314 Part B. Lecture Overview Functions Function Prototypes Function Definitions…

RECURSION

Page 41: Functions Skill Area 314 Part B. Lecture Overview Functions Function Prototypes Function Definitions…

RECURSION

• A function can call itself. • This is called recursion, and

recursion can be direct or indirect.

• It is direct when a function calls itself; it is indirect recursion when a function calls another function that then calls the first function.

• It is useful for many tasks, like sorting or calculate the factorial of numbers. 

Page 42: Functions Skill Area 314 Part B. Lecture Overview Functions Function Prototypes Function Definitions…

RECURSION#include <iostream>using namespace std; void CountDown(int nValue);int main(){ CountDown(10); return 0;}void CountDown(int nValue){ cout << nValue << endl; // termination condition if (nValue > 0) CountDown(nValue-1); //RECURSION}

Page 43: Functions Skill Area 314 Part B. Lecture Overview Functions Function Prototypes Function Definitions…

--- continue to next slide ---