Functions in CPLUSPLUS


functions
Image credit: http://mathbits.com

Functions in CPLUSPLUS

Being an I.T professional; to the point and brief discussion is very important.Functions in CPLUSPLUS are the collection of statements that executed only when, if they are being invoked. In short, we make function to save our time and every computer resource utilization by preventing the same logic by writing many lines of code again and again.
The sketch of C++ function is:

return_type method_name(parameters_list)// declaration of function
{

// body of a function with statements or calculations

}


The method with all its prerequisites is the declaration of the function, but we have to do nothing with that declaration, we want function to work. The whole function with body brackets “{}” with statements in it or our logical work is the definition of a function.

Function with Parameters

In normal programming term, parameters or arguments are the user supplied information to the function so that it works per desire.
Let’s see it:

#include “stdafx.h”
#include <iostream>
using namespace std;// namespace for standard functions

// a method of returning type integer and it takes three variables as parameters
int Summation(int a, int b, int c)
{
// sum of the variables is stored in sum variable
int sum= a+b+c;
// returning the calsulated value to the Summation function
return sum;

}

int main()
{
// i will get the result of the values passed and returning the result to summation method
int i=Summation(1,2,3);

cout<< "Sum of a+b+c:"; cout<< i; cout<< endl; return 0; } }

Output

Passing pointers as argument in function
In this program, we will write a code just like in C language. cout>> hs been replaced by Printf function. This is easily possible if we look at the code above where these files are addressed. Let’s see a program:

    Example
    #include

    int swap_ints(int *first_number, int *second_number);

    int
    main()
    {
    int a = 4, b = 7;

    printf(“pre-swap values are: a == %d, b == %dn”, a, b)

    swap_ints(&a, &b);

    printf(“post-swap values are: a == %d, b == %dn”, a, b)

    return 0;
    }

    int
    swap_ints(int *first_number, int *second_number)
    {
    int temp;

    /* temp = “what is pointed to by” first_number; etc… */
    temp = *first_number;
    *first_number = *second_number;
    *second_number = temp;

    return 0;
    }

Syed Adeel Ahmed
Syed Adeel Ahmed
Analyst, Programmer, Educationist and Blogger at Technofranchise
Computer Systems Engineer from Sir Syed University Of Engineering & Technology.I am passionate about all types of programming.

Published by

Syed Adeel Ahmed

Computer Systems Engineer from Sir Syed University Of Engineering & Technology.I am passionate about all types of programming.