430 likes | 670 Views
Functions. Skill Area 314 Part B. Materials Prepared by Dhimas Ruswanto , BMm. Lecture Overview. Functions Function Prototypes Function Definitions Local Variables Globa l Variables Default Parameters Overloaded Functions Passing by Value Passing by Reference Inline Functions
E N D
Functions Skill Area 314 Part B Materials Prepared by DhimasRuswanto, BMm
Lecture Overview • Functions • Function Prototypes • Function Definitions • Local Variables • Global Variables • Default Parameters • Overloaded Functions • Passing by Value • Passing by Reference • Inline Functions • Recursion
What is a FUNCTION? • A function is a group of statements that is executed when it is called from some point of the program.
FUNCTION PROTOTYPE FUNCTION DEFINITION
Declaration and Definition • Using functions in your program requires that you first declare the function and that you then define the function. • The declarationtells the compiler the name, return type, and parameters of the function. • The definitiontells 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.
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. Parameter type Parameter name name intfindArea (int length, int width); semicolon return type parameters
Function Prototype • Prototype that looks like this is perfectly legal (without parameter name): intfindArea (int,int); • 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 intfindArea (intheight,intwidth);
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_typefunction_name ( [typeparameterName]...) { statements; } int area ( int height, int width) { return height* width; }
Function Definition return_typefunction_name ( [typeparameterName]...) { statements; } • 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 { }.
NOTE • The function prototype and the function definitionmust agree exactly about the return type, the name, and the parameter list. • If they do not agree, you will get a compile-time error.
Functions #include <iostream> using namespace std; int add (int a, int b); //function prototype int main () { int x=1, y=3; cout << "x + y= "<< add(x,y); //calling function add() system ("pause"); return 0; } //function definition int add (int a, int b) { returna+b; }
NOTE • If you try to placing the a function before the main() function without declared the function first, you will have compile-time error
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 void printmessage() ; //function prototype //function definition void printmessage () { cout<< “I’m a function!”; }
Functions with no Type (VOID) // void function example #include <iostream> usingnamespacestd; voidprintmessage (); //function prototype int main () { printmessage (); return 0; } //function definition voidprintmessage () { cout << "I'm a function!"; }
Functions with no Type (VOID) // void function example #include <iostream> usingnamespacestd; void subtract(int a, int b); //function prototype int main () { int x=7, y=2; subtract (x,y); return 0; } //function definition void subtract(int a, int b) { int c; c=a-b; cout << c; }
LOCAL VARIABLES GLOBAL VARIABLES
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.
Scope of Variables #include <iostream> using namespace std; int multiply (int a, int b); int x=5, y=6; //GLOBAL variables int main() { inti=7,j=9; //LOCAL variables cout << multiply(i,j) << endl; cout<< multiply(x,y); return 0; } int multiply (int a, int b) { int z; //LOCAL variables z=a*b; return z; }
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.
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 intfindArea (intheight,intwidth); intfindArea (intheight = 50,intwidth=75);
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 intmyFunction (intParam1,intParam2, int Param3);
DEFAULT Parameter #include <iostream> using namespace std; int divide (int a, int b=2); //function prototype int main () { cout << divide (12); cout << endl; cout << divide (20,4); return 0; } //function definition int divide (int a, int b) { int r; r=a/b; return (r); }
DEFAULT Parameter #include <iostream> using namespace std; intAreaCube(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(intlength, int width, int height) { return (length * width * height); }
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 overloadingis also called function polymorphism. Poly means many, and morph means form: a polymorphic function is many-formed.
OVERLOADED Functions #include <iostream> using namespace std; int operate (int a, int b); float operate (float a, float b) intmain () { 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); }
Passing by VALUE int x=5, y=3, z; z = addition ( x , y ); • 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. • 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.
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.
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
Passing by REFERENCE • //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 //with ampersand sign (&) #include <iostream> using namespace std; void operate(int& a); int main () { int x=3; operate(x); cout << x; return0; } void operate (int& a) { a=2; } --------------------------------- Output: 2
Passing by REFERENCE // more than one returning value #include <iostream> using namespace std; voidprevnext (int x, int& prev, int& next); intmain () { int x=100, y, z; prevnext (x, y, z); cout << "Previous=" << y << ", Next=" << z; return 0; } voidprevnext (int x, int& prev, int& next) { prev = x-1; next = x+1; }
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.
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.
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.
INLINE Functions • The format for its declaration is: inline type name ( arguments ... ) { instructions ... }
INLINE Functions #include <iostream> using namespace std; intexforsys(int); int main( ) { int x; cout << "n Enter the Input Value: "; cin>>x; cout << "n The Output is: " << exforsys(x); return 0; } inlineintexforsys (intx1) //INLINE Function { return 5*x1; }
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.
RECURSION #include <iostream> using namespace std; voidCountDown(intnValue); intmain() { CountDown(10); return 0; } voidCountDown(intnValue) { cout << nValue << endl; // termination condition if (nValue > 0) CountDown(nValue-1); //RECURSION }