Friday, December 28, 2012

Journey through Function to Method ....part _1

This post is going to be in 2 part
in 1st part, we dicuss about FUNCTION
& in 2nd part, we discuss about METHOD

Functions:
A function is a block of code that has a name and it has a property that it is reusable i.e. it can be
executed from as many different points in a Program as required.
  • Function helps us to achieve modularity.
  • Function also helps to achieve encapsulation (data + operation).

Why we use Functions:
1. Writing functions avoids rewriting the same code over and over.
2. Using functions it becomes easier to write programs and keep track of what they are doing

Syntax of  Function:
<function-type> <function-name> ()
{
       /*   code    */
}

Function has 2 parts:
1. Function declaration (function prototype)
2. Function definition
___________________________________________________________________
#include<iostream>
using namespace std;

//function prototype for a function named add     
int add (int x, int y);          //this is declartion of function also
                                     //before using function it must be declared  
int main()
{
    int result = add ( 1, 2 );     //here we are calling the add function
    cout << "The result is: "<< result << '\n';
    cout << "adding 3 and 4 gives us: "<< add ( 3, 4 ) << endl;
    cout << "adding 3 and 4 gives us: "<< 3 + 5;
}

//------this is definition of a function--------
int add (int x, int y)        
{                             
    return x + y;              
}
//if we are defining a funtion, before main() we don't need to do prototype
____________________________________________________________________

  •  int add ( );
Function declarations are also called prototypes, since they provide a model or blueprint for the function.
             They tell the compiler,” a function that looks like this is coming up later in the program, so it”s all right if you see references to it before you see the function itself.”

  •  Function definition:
The definition contains the actual code for the function. Here’s the definition for Demo( ).

void Demo ( )            //this is also known as function header
{
    for ( intj=0, j < 45; j++ )
    cout << "*" ;
    cout << endl;
}
  • The only difference between the header and the prototype is the semicolon ; there must the a semicolon at the end of the prototype.

  • add();
       This is all we need to call a function. name, followed by parentheses.

  • There are basically two types of functions:
       1. Library functions Ex. printf ( ), scanf ( ), pow() etc.
       2. User defined function e.g the function message mentioned above.

Please Remeber these:
  1.  Any function can be called from any other function even main ( ) can be called from other functions.
  2.  A function can call itself such a process as called “recursion”.
  3. A function can be called from other function, but a function cannot be defined in an-other function.
  4. After each function has done its thing, control returns to the main( ), when main( ) runs out of function calls, the program ends.

Term assocaited with function (you must known):
  1. Argument
  2. parameters
  3. invoke (calling)
  4. Return Type
  5. scope

The basic about function is complete here. Now you can jump into 2nd part of this post which is Journey through Function to Method ....part _2

In case you want to known more about Function, then go ahead....
                 In computer science, a subroutine, also termed procedure, function, routine, method, or subprogram, is a part of source code within a larger computer program that performs a specific task and is relatively independent of the remaining code.
            As the name subprogram suggests, a subroutine behaves in much the same way as a computer program that is used as one step in a larger program or another subprogram. A subroutine is often coded so that it can be started (called) several times and/or from several places during one execution of the program, including from other subroutines, and then branch back (return) to the next instruction after the call once the subroutine's task is done.

Things to remember while thinking about function:
·      delimit the part of the program (body) that makes up the subroutine
·      assign an identifier (name) to the subroutine
·      specify the names and/or data types of its parameters and/or return values
·      provide a private naming scope for its temporary variables
·      identify variables outside the subroutine that are accessible within it
·      call the subroutine
·      provide values to its parameters
·      specify the return values from within its body
·      return to the calling program
·      dispose of the values returned by a call
·      handle any exceptional conditions encountered during the call
·      package subroutines into a module, library, object, class, etc.

Advantages:

The advantages of breaking a program into subroutines include:
  • Decomposing a complex programming task into simpler steps: this is one of the two main tools of structured programming, along with data structures
  • Reducing duplicate code within a program
  • Enabling reuse of code across multiple programs
  • Dividing a large programming task among various programmers, or  various stages of a project
  • Hiding implementation details from users of the subroutine
  • Improving traceability, i.e. most languages offer ways to obtain the call trace which includes the names of the involved subroutines and perhaps even more information such as file names and line numbers; by not decomposing the code into subroutines, debugging would be impaired severely.

 

Disadvantages:

  • Invoking a subroutine (versus using in-line code) imposes some computational overhead in the call mechanism.
  • The subroutine typically requires standard housekeeping code – both at entry to, and exit from, the function (function prologue and epilogue – usually saving general purpose registers and return address as a minimum).

 

Call stack: (How function internally handled by compiler)

Most modern implementations use a call stack, a special case of the stack data structure, to implement subroutine calls and returns. Each procedure call creates a new entry, called a stack frame, at the top of the stack; when the procedure returns, its stack frame is deleted from the stack, and its space may be used for other procedure calls. Each stack frame contains the private data of the corresponding call, which typically includes the procedure's parameters and internal variables, and the return address.

By value:

A way of passing the value of an argument to a procedure instead of passing the address. This allows the procedure to access a copy of the variable. As a result, the variable's actual value can't be changed by the procedure to which it is passed.

By reference:

A way of passing the address of an argument to a procedure instead of passing the value. This allows the procedure to access the actual variable. As a result, the variable's actual value can be changed by the procedure to which it is passed. Unless otherwise specified, arguments are passed by reference.

Public (optional)

Indicates that the function procedure is accessible to all other procedures in all modules. If used in a module that contains an Option Private, the procedure is not available outside the project.

Private (optional)

Indicates that the function procedure is accessible only to other procedures in the module where it is declared.

Friend (optional)

Used only in a class module. Indicates that the Function procedure is visible throughout the project, but not visible to a controller of an instance of an object.

Inlining :

A method used to eliminate this overhead is inline expansion or inlining of the subprogram's body at each call site (versus branching to the subroutine and back). Not only does this avoid the call overhead, but it also allows the compiler to optimize the procedure's body more effectively by taking into account the context and arguments at that call. The inserted body can be optimized by the compiler. Inlining however, will usually increase the code size, unless the program contains only one call to the subroutine, or the subroutine body is less code than the call overhead.

More about inline function CLICK HERE

Now we are ready to move to the second part of this article in which we discuss about the METHOD.

No comments:

Post a Comment