Thursday, 15 March 2012

INLINE FUNCTIONS



DEFINITION:
An inline function is one for which the compiler copies the code from the function definition directly into the code of the calling function rather than creating a separate set of instructions in memory. Instead of transferring control to and from the function code segment, a modified copy of the function body may be substituted directly for the function call. In this way, the performance overhead of a function call is avoided.

A function is declared inline by using the inline function specifier or by defining a member function within a class or structure definition. The inline specifier is only a suggestion to the compiler that an inline expansion can be performed; the compiler is free to ignore the suggestion.
The following code fragment shows an inline function definition:
inline int add(int i, int j)
 {
      return i + j;
 }
The use of the inline specifier does not change the meaning of the function. However, the inline expansion of a function may not preserve the order of evaluation of the actual arguments. Inline expansion also does not change the linkage of a function: the linkage is external by default.
         In C++, both member and nonmember functions can be inlined. Member functions that are implemented inside the body of a class declaration are implicitly declared inline. Constructors, copy constructors, assignment operators, and destructors that are created by the compiler are also implicitly declared inline. An inline function that the compiler does not inline is treated similarly to an ordinary function: only a single copy of the function exists, regardless of the number of translation units in which it is defined.
        In C, any function with internal linkage can be inlined, but a function with external linkage is subject to restriction. . The restrictions are as follows:
If the inline keyword is used in the function declaration, then the function definition must appear in the same translation unit.
An inline definition of a function is one in which all of the file-scope declarations for it in the same translation unit include the inline specifier withoutextern.
An inline definition does not provide an external definition for the function: an external definition may appear in another translation unit. The inline definition serves as an alternative to the external definition when called from within the same translation unit. 
        In the Ada programming language, there exists a pragma for inline functions. Most other languages, including Java and functional languages, do not provide language constructs for inline functions, but often do perform aggressive inline expansion.

ADVANTAGES:
  • It saves the time required to execute function calls.
  • Small inline functions, perhaps three lines or less, create less code than the equivalent function call because the compiler doesn't generate code to handle arguments and a return value.
  • Functions generated inline are subject to code optimizations not available to normal functions because the compiler does not perform inter procedural optimizations.
DISADVANTAGES:
  •  Inlining can increase the size of your executable program significantly leading to more number of page faults bringing down program performance.
  •  If used in header file, it will make your header file size large and may also make it unreadable.
DIFFERENCES BETWEEN INLINE FUNCTIONS AND MACROS:

  •  Macro is expanded by preprocessor and inline function are expanded by compiler.
  •  Expressions passed as arguments to inline functions are evaluated only once while expression passed as argument to inline functions are evaluated more than once. 
  • Inline functions are used to overcome the overhead of function calls. Macros are used to maintain the readability and easy maintainence of the code.
  • Debugging is tough in macros (because they refer to the expanded code, rather than the code the programmer typed) whereas debugging is easy in inline functions.
  • Macro invocations do not perform type checking, or even check that arguments are well-formed, whereas function calls usually do.
  •  A macro cannot return anything which is not the result of the last expression invoked inside it but in inline functions we can return any value by using keyword return();

Thursday, 8 March 2012

SWAPPING IN JAVA



In Java the swap function works if we use wrapped integers and pass references to them to the function. However, the Java wrapper class for int is Integer and it doesn't allow to alter the data field inside. Thus we need our own wrapper class (MyInteger below).


 // MyInteger: similar to Integer, but can change value
class MyInteger
{
 private int x;     // single data member
 public MyInteger(int xIn)
 {
                x = xIn;
 } // constructor
 public int getValue()
 {
               return x;
 }  // retrieve value
 public void insertValue(int xIn)
 {
              x = xIn;
} // insert
}

public class Swapping
{
   // swap: pass references to objects
  static void swap(MyInteger rWrap, MyInteger sWrap)
 {
      // interchange values inside objects
      int t = rWrap.getValue();
      rWrap.insertValue(sWrap.getValue());
      sWrap.insertValue(t);
   }

   public static void main(String[] args)
 {
      int a = 23, b = 47;
      System.out.println("Before. a:" + a + ", b: " + b);
      MyInteger aWrap = new MyInteger(a);
      MyInteger bWrap = new MyInteger(b);
      swap(aWrap, bWrap);
      a = aWrap.getValue();
      b = bWrap.getValue();
      System.out.println("After.  a:" + a + ", b: " + b);
   }
}


FUNCTION POINTERS


DEFINITION:
 A function pointer is a variable that stores the address of a function that can later be called through that function pointer. This is useful because functions encapsulate behavior. For instance, every time you need a particular behavior instead of writing out a bunch of code, all you need to do is call the function. But sometimes you would like to choose different behaviors at different times in essentially the same piece of code.A function pointer always points to a function with a specific signature! Thus all functions, you want to use with the same function pointer, must have the same parameters and return-type!
          There are 2 types of function pointers:
1.Pointers to ordinary C functions or to static C++ member functions.
2.Pointers to non-static C++ member functions.
The basic difference is that all pointers to non-static member functions need a hidden argument.
SYNTAX:
                          void (*foo)(int);
 foo is a pointer to a function taking one argument, an integer, and that returns void. It's similar to  declaration of a function called "*foo", which takes an int and returns void. If *foo is a function, then foo must be a pointer to a function.
INITIALIZING: 
To initialize a function pointer,  the address of a function in program must be given to it. The syntax is like any other variable:

You can get the address of function simply by naming it.
                            void  foo();
                           func_pointer = foo;
or by prefixing the name of the function with an ampersand
                            void foo();
                           func_pointer = &foo;


INVOKING:
Invoke the function pointed similar to calling a function.
                        func_pointer( arg1, arg2 );

COMPARING FUNCTION POINTERS:
 The comparison-operators (==, !=) are used to compare function pointers.

USES:
1. Functions as Arguments to Other Functions
2.Callback Functions


BENEFITS:
Function pointers provide a way of passing around instructions for how to do something
You can write flexible functions and libraries that allow the programmer to choose behavior by               passing function pointers as arguments
This flexibility can also be achieved by using classes with virtual functions.




Tuesday, 6 March 2012

JAVA COMPILATION PROCESS




Java code does not compile to native code that the operating system executes on the CPU, rather the result of Java program compilation is intermediate bytecode. This bytecode runs in the virtual machine.

Java requires each class to be placed in its own source file, named with the same name as the class name and added suffix .java. This basically forces any medium sized program to be split in several source files. When compiling source code, each class is placed in its own .class file that contains the bytecode. The java compiler differs from gcc/g++ in the fact that if the class you are compiling is dependent on a class that is not compiled or is modified since it was last compiled, it will compile those additional classes. After compiling all source files, the result will be at least as much class files as the sources, which will combine to form Java program. This is where the class loader comes into picture along with the bytecode verifier - two unique steps that distinguish Java from languages like C/C++.

The class loader is responsible for loading each class bytecode. Java provides developers with the opportunity to write their own class loader, which gives developers great flexibility. One can write a loader that fetches the class from everywhere.

STEPS TAKEN BY A LOADER TO LOAD A CLASS:
When a class is needed by the JVM the loadClass(String name, Boolean resolve); method is called passing the class name to be loaded. Once it finds the file that contains the byte code for the class, it is read into memory and passed to the defineClass. If the class is not found by the loader, it can pass the loading to a parent class loader or try to use findSystemClass to load the class from local file system. The Java Virtual Machine Specification is vague on the subject of when and how the Byte Code verifier is invoked, but by a simple test we can infer that the defineClass performs the bytecode verification. The verifier does four passes over the bytecode to make sure it is safe. After the class is successfully verified, its loading is completed and it is available for use by the runtime.

The nature of the Java byte code allows people to easily decompile class files to source. In the case where default compilation is performed, even variable and method names are recovered.

Labels