How to Use Functions in C++

The objective of any programming language is to provide thousands of types of solutions for any sector. Apart from making a good program, your code should also be efficient and well organised so that it is easy for anyone to debug hence shortening the code is an idea. You can do this by using methods or functions. Functions are set of instructions that are executed each time that function is called from anywhere inside the code. All of the programming languages have hundreds off built in functions but you can also write new functions to fulfill your needs. Following step by step guide will show you how you can play around with functions in C++.

Instructions

  • 1


    Declaration, initialization, and Body


    To write and use any of the function in C++, you first need to declare it inside your program, to declare a function use following syntax.


    Return_type    name_of_function(parameter1, parameter2,….);


    {


    //Functions body statements


    }


    Where:
    a: Return_type is the data type or value returned by the function.
    b: Name_of_function is the desired name of your function.
    c: Parameter1, parameter2 … are the input parameters that you need to pass to the function while calling it.
    d: Inside braces you have to write the set of instructions, you need to execute every time.



  • 2


    Once you are done with declaring the function and all of its body statements, you can call it from anywhere inside your program.



  • 3


    The variables declared inside a function are local to that function only and no one can access them outside that function. But variables declared above the main function of your program are global variables and they can be accessed by your function.



  • 4


    Example:


    To demonstrate functions well, I am writing this example function which will calculate sum of two longs every time it is called.


    #include


    using namespace std;


    long add_longs (long no1, long no2)


    {


    long result;


    result=no1+no2;


    return (result);


    }


    int main ()


    {


    long temp;


    long a=45;


    long b=10;


    temp = add_longs(a,b);


    cout << "Result of addition = " << temp;


    return 0;


    }



Leave a Reply

Your email address will not be published. Required fields are marked *


five + 4 =