C++: Functions-2

Call By Reference:

When we pass arguments by reference, the 'formal' arguments in the called function become aliases to the 'actual' arguments in the calling function.

  void swap(int a,int b)//a and b are reference variables
        int t=a;

the function  will be

Inline Function:

An  inline function is a function that is expanded in line when it is invoked. That is, the compiler replaces the function call
with the corresponding functionn code.

    inline function-header
           function body
     inline double cube(double a){

All inline function be defined before they are called.

The inline keyword merely sends a request, not a command, to the compiler. The compiler may ignore this request if the function definition is too long or too complicated and treat it as a normal function.

Some of the situations where inline expansion may not work are:

  1. For functions returning values,if a                loop,a switch, or a goto exits.

   2. For functions not returning values, if a return statement exists.
   3. If functioin contain static variables.

   4. if inline functions are recursive.

Default Argument:

  float amt(float principal,int period,float rate=0.15);

The above prototype declares a default value of 0.15 to the argume
nt rate.

  value=amt(1000,2); //one argument missing

  value=amt(1000,2,0.10); //no argument missing

The above function call passses value of 0.10 to rate.

Only the trailing arguments can have default values.

We must add defaults from right to left and cannot provide a default value to a particular argument in the middle of an argument list.

  int add(int i,int j=2,int k=4);// legal
  int add(int i=1,int j);// illegal

const Arguments:

   int strlen(const char *p);
   int  length(const string &s);

The qualifier const tells the compiler that the function should not modify the argument.

This type of declaration is significant only when we pass arguments by reference or pointers.

Function  Overloading:

We can use same function name with different argument list to perform a variety of different task and known as function polymorphism in  OOP.

  int add(int a,int b);// prototype 1
  int add(int a,int b,int c);// prototype 2
  int add(float a,float b);// prototype 3

I have not discussed some topic such  as loops and switch because you can find them in every book.I have discussed some topics and points which we failed to notice or forgot when we read book.

            < Happy Coding >


In Association with Amazon.in