C++ Functions

Function


Function is a block of code used to perform particular task. We can create one or more functions in program but the program execution starts from main() function. function can be called within each other.

Advantage of Function


  • Reusability of code: function can be called many times again and again.
  • Reduce complexity of program
  • Function divide bigger program into smaller section, so it become easier to understand program.
  • Execution speed of program increases.
  • Syntax Of Function


    
    void myfunction()
    {
        Block Of Code;
    }
    
    

    • myfunction refers function name
    • void means that function does not have any return value.
    • Block of Code refers code which need to execute on calling

    Types of Function


    There are 2 types of function :
    1. Library Function
    2. User Defined Function

    Library Function


    There are predefined functions provided by C++. These functions exist in header files. E.g clrscr(), getch(), etc.

    User Defined Function


    These are defined by programmer or user according to their requirement. Use defined functions are used to perform specific task. Also can be use multiple times.

    Program to show use of function.


    
    #include<iostream.h>
    #include<conio.h>
    void funct()
    {
        int a,b,c;
        a=10;
        b=5;
        c=a+b;
        cout<<"Sum = "<<c;
    }
    void main()
    {
       clrscr();
       funct();           // function
       getch();
    }
    
    

    Output

    
    Sum=15
    
    

    Back To Top