Functions In C++ - TGN

Latest

Welcome to Technicalgurunow! Your No. 1 source for all networking , earning and programming tutorials. We're dedicated to providing you the best of knowledgeable information with a focus on dependability. We hope you enjoy our blog.

Tuesday, March 3, 2020

Functions In C++

What is Function?


  • A function may be a group of statements that together perform a task.
  • Every program in C++ has atleast one function which is main( ) function.
  • We can divide our code into separate functions.
  • A function is also known as method in C++.
  • A function declaration tells the compiler about a function name, its return type and parameters passed to the function.
  • A function definition provides the actual body of function.
  • When the function is named, control is transferred to the primary statement within the function body.
  • The parameters or an arguments which appear in function call statements are known as actual parameters or an arguments.
  • The parameters or an arguments which appear in function declaration which has been called are known as formal parameters or formal arguments.
  • Syntax:-

           return_type function_name(parameter);  //Function declaration
           {
                 Body of function
            }


A C++ function definition consists of a function header and a function body:-

Return_type:-A function may return a value.The return_type is the data type of the value. Some functions perform the particular operations without returning a value. In this case, the return_type is that the keyword void.

Function_name:-This is the actual name of the function.

Parameter:-When a function is called, we pass a value to the parameter. Paramter refers to the data_type, sequence and number of parameters of a function. Some functions may contain no parameters.

Function body:-The function body contains a group of statements that define what the function does.




The main( ) function:-


  • In C++, the main( ) function returns a value of type int to the Operating System.
  • C++, therefore, explicitly defines main( ) as matching to one of the following prototypes:-


        int main( );
        int main(int argc, char *argv[ ]);

  • The functions that have return value should use the return statement for termination of a program.

         int main( )
        {
            //code;
            return 0;
        }

  • Most of the C++ Compilers will generate an error or warning if there is no return statement.
  • The explicit use of a return 0; statement will indicate that the program was successfully executed, while non-zero value means there was a error.


Function Calling Techniques:-

     1.Call By Reference:-

  • When we want to change the values of variables in the calling program, we use call by reference method.
  • Incase of Call by Reference, we pass argument and that data is catch in reference variable.
  • When we pass arguments by reference, the 'formal' arguments in the called function became aliases to the 'actual' arguments in the calling function. This means that when the function is functioning with its own arguments, it it's actually performing on the first data.
  • It is a method of passing arguments to the function by copying the reference of an argument into the 'formal' parameter.
  • e.g.:-
      void refer(int &a, int &b)             //a and b are reference variables
      {
          int i=a;
              a=b;
              b=i;
       }

     2.Call By Address:-

  • Also known as Call By Pointer.
  • Incase of Call by Address, we call the function by passing an address of variables. And that address is catch in a pointer.
  • It is necessary to use pointer as formal arguments in order to implement call by address in C++.
  • Since, there is use of pointer, the changes done by formal arguments will be reflected in actual arguments.
  • Actual and Formal arguments points to the different location in memory but, as the formal arguments stores the address of actual arguments, so they share the same value in memory.
  • e.g.:-
      #include<iostream>
      #include<conio.h>
   
      void display(int *ptr)
      {
            cout<<"address of number incase of call by address"<<&ptr<<endl;
      }

       int main( )
       {
            int i=10;
            cout<<"address of i:"<<&i<<endl;
            display(&i);
        }


     3.Call By Value:-

  • Incase of Call By Value, when function is called the value of the actual parameters is copied into the formal parameters.
  • Actual and Formal arguments both have their own copies of values. That means any change in one of the type of arguments will not be reflected by another. It is because Actual and Formal arguments both points to different memory address location.
  • This method is useful when we don't want values of actual arguments to be changes by different functions.
  • e.g.:-
       #include<iostream>
       #include<conio.h>
       
        void display(int no)
        {
             cout<<"address of no incase of call by value"<<&no<<endl;
        }
         int main( )
         {
             int i=10;
             cout<<"address of i:"<<&i<<endl;
             display(i);
             return(0);
          }

Inline Functions:-

  • Everytime a function is called, it takes a lot of extra time in executing a series of instructions for tasks such as jumping to the function, saving registers, pushing arguments to the stack and returning to the calling function. When function is small, a substantial percentage of execution time may be spent in such overheads.
  • In C, macro definitions are used, popularly known as macros. Preprocessor macros are popular in 'C'
  • But macros are not really a functions and therefor the usual error checking does not occur during compilation.
  • So, in C++, to reduce the cost of calls to small function, a new feature is used known as 'inline function'.
  • An inline function is a function that is expanded in line when it is invoked. That is compiler replaces the function call with the corresponding function code.
  • We need to prefix the keyword 'inline' to the function definition. All inline functions must be defined before they are called.
  • 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 compile the function as a normal function.
  • Some situatons where inline expansion may not work:-

       (i) For functions returning values, if a loop, a switch. or a goto exists.
       (ii) For functions not returning values, if a return statement exists.
       (iii) If functions contain static variables.
       (iv) If inline functions are recursive.

  • Syntax:
      inline function_header
      {
           function_body
      }

  • e.g.:-
      class demo
      {
         public:
                 inline void add(int r, float pi=3.14)
                 {
                     float area=pi*r*r;
                     cout<<"area";
                 }
      }
  
       int main( )
       {
            demo obj;
            obj.add(10);

            return(0);
       }



Default Arguments:-

  • When we write a function, it accepts some values from user.
  • If user is not able to pass an argument or variable value, then it is considered as a default argument or default value.
  • A default argument is checked for type at the time of declaration and evaluated at the time of call
  • Default arguments are useful in situations where some arguments always have the same value.
  • We can use default arguments to add new parameters to the existing functions.
  • Default arguments can be used to combine similar functions into one function.
  • e.g.:-
     void area(int r, float pi=3.14)     //float pi=3.14 is a default argument
     {
          float ans;
          ans=pi*r*r;
          cout<<ans;
     }
       int main( )
       {
           area(10, (22/7));
           area(10);
           area( );                  //error

          return(0);
        }


Rule for Default Arguments:-


  • Default arguments should always be in a right to left order otherwise compiler will give an error.
  • e.g.:-

    void fun(int i=11, int j, int k)                        //error
    void fun(int i, int j=11, int k)                       //error
    void fun(int i, int j, int k=11)                      //allowed
    void fun(int i, int j=10, int k=11)               //allowed
    void fun(int i=15, int j=10, int k=11)        //error



No comments:

Post a Comment

If you have any query, please let me know

Followers