C++

C++ Functions

C++ Functions

Let us look at C++ methods or functions. A function or a method is a block of code that gets executed when it is called. Functions are used to perform certain actions, and they are important for modular programming specially reusing code i.e. define the code once, and use it many times. A function is a set of statements that as a whole accomplish a task. Every C++ program has at least one function i.e. main () which is the entry point of the program. A program is said be following modular approach ifs functionality is split into multiple functions. A function is also called as a method or a sub-routine or a procedure etc.

Most of the programmers split their code into separate functions based on logically dividing a specific task into a number of functions. For e.g in order to write a calculator CLI based application, we need functions to present menu, function to add, subtract, multiple, divide and do modulo operation, function to display result etc. 

A function declaration or its signature consists of its name, its return type, and set of parameters passed to it. Its syntax is

<return_type> functionName (list of formal parameters with type and name  like <type> name, <type> name ...);

For e.g.

int addTwoInt( int &a, int &b);

A function definition provides the actual body of the function. A complete function thus looks like this

return_type function_name( parameter list ) 
{
   //body of the function
   ...
}

A C++ function definition consists of a function header (the declaration part without semicolon) and a function body. Let us explain each part briefly:

Return Type it is the type of object that the functions returns. It may or may not be present.  A function may return a value. In case where the function does its work but has nothing to return, you must use the return_type as void.

  1. Function Name it is the name of the function by which i is called. The function name and the parameter list together constitute the function signature.
  2. Parameters or arguments− it is actually a placeholder for compiler to know what kind of object is passed to the function. A function is invoked by passing it a value as an argument. The parameter list refers to the type, order, and number of the parameters of a function. Parameters may or may not be present.
  3. Function or method body − it is where the entire logic to achieve the designated task resides for the method. It is a group of statements enclosed in {}.

The C++ standard library provides numerous built-in functions that your program can call. For example, function strcat() to concatenate two strings, function memcpy() to copy one memory location to another location and many more functions.

In order to use a function you need to call it or invoke it by supplying it the required arguments and storing its return value in a return_type variable (if the functions returns something). For e.g consider the following simple program to add two integers. Copy the following code in a sile say simpleAdd.cpp

#include <iostream>
using namespace std;

/* 
 * Formal function signature. 
 * Note parameters passed as const refences so 
 * that function does not unintentionally modify them
 */
int addInt( const int &n1, const int &n2 );

int main()
{
    int num1=10;
    int num2=20;
    int sum;
    
    //Invoke the function sum by passing argument nuk1 and num2 and store output in sum
    sum = addInt(num1, num2);

    //Display the result
    cout<<"Sum of "<<num1<<" and "<<num2<<" is: "<<sum<<endl;
}


int addInt( const int &n1, const int &n2 )
{
    return (n1+n2);
}

Now compile and execute the code

(base) 9:09:13:~ % g++ simpleAdd.cpp

(base) 9:09:14:~ % ./a.out               

Sum of 10 and 20 is: 30

We can specify a default value to any parameter in function definition. This value will be used if the corresponding argument is left blank when calling to the function. It can be done by assigning a value to the parameter using assignment operator. If no value is passed for that parameter in function invoking, the default given value is used, but if a value is specified, this default value is ignored and the passed value is used instead. See the declaration of addInt () below for default value 

int addIntDefault( const int &n1, const int &n2 = 100 );

Let us modify the program simpleAdd.cpp by making use of default values. Copy the following code in a file say simpleAddDefault.cpp

#include <iostream>
using namespace std;

/* 
 * Formal function signature. 
 * Note parameter n2 has default value of 100
 */
int addIntDefault( const int &n1, const int &n2 = 100);

int main()
{
    int num1=10;
    //int num2=20;
    int sum;
    
    //Invoke the function sum by passing argument nuk1 and num2 and store output in sum
    sum = addIntDefault(num1);

    //Display the result
    cout<<"Sum of "<<num1<<" and 100 is: "<<sum<<endl;
}


int addIntDefault( const int &n1, const int &n2 )
{
    return (n1+n2);
}

Now compile the code and execute. Here we invoke addIntDefault() using default value of 100 for n2 and passing 10 for n1 to get a sum of 110.

(base) 9:23:56:~ % g++ simpleAddDefault.cpp
(base) 9:23:59:~ % ./a.out                 
Sum of 10 and 100 is: 110

When a program calls a function, program control is transferred from caller function to the called function. A called function performs defined task and when it’s return statement is executed or when its function-ending closing brace is reached, it returns program control back to the caller. Functions are usually performed using Stack data structure. 

The formal parameters or formal arguments (variables that we pass to a function when calling it) are like other local variables inside the function and are created upon entry into the function and destroyed upon exit. We can pass arguments to a function using two ways

  1. Call by Value here actual value of an argument gets copied into the formal parameter of the function ( a new copy is created via deep copy operation ). Since, formal parameter is a new variable, changes made to it inside the function have no effect on the actual argument passed from caller function. We can pass the argument either by value or by pointer. for case of pointer, the method copies the address of an argument into the formal parameter i.e makes a new pointer variable but pointing to the same memory location. Inside the called function, the address is used to access the actual argument used in the call and thus any change done on formal parameter can affect the value of original argument in the caller function.
  2. Call by Reference here no deep copy is done but shallow copy is done. It copies the reference of an argument into the formal parameter. 

Here actual and formal arguments share the same address space. Thus any change done in called function will get reflected in the caller function.

In this section, let us ponder over numbers in C++. We referent fixed point numbers using in and floating point numbers using float and double depending upon their length and precision needed. C++ uses the + operator for both addition and string concatenation. This is possible due to polymorphism and operator overloading. 

The C++ numerics library provides common mathematical functions and types, as well as optimized numeric arrays and support for random number generation. For instance, the header <numbers>  part of numerics library provides several mathematical constants, such as std::numbers::pi or std::numbers::sqrt2.

Let us write a sample program to check if a given number is palindrome or not. A palindrome number is a number which when read from reverse side is same as the original number. For e.g 56744765.

Copy the following code in a file say palindrome.cpp.

#include <iostream>
using namespace std;

int main()
{
    int i,num,r,s=0;
    cout << " ------------------------------------------------------------------\n";
    cout << "\n\n Program to check whether a given number is palindrome or not: \n";
    cout << " ------------------------------------------------------------------\n";
    cout << "Input a number: ";
    cin>>num;   
    for(i=num;i>0; )
    {
        r=i % 10;
        s=s*10+r;
        i=i/10;
    }
    if(s==num)
    {
        cout<<" "<<num<<" is a Palindrome Number."<<endl;
    }
    else
    {
        cout<<" "<<num<<" is a not Palindrome Number."<<endl;
    }
}

Now compile and execute the program

(base) 9:38:19:~ % g++ palindrome.cpp 

(base) 9:38:25:~ % ./a.out 

 

 ------------------------------------------------------------------

 Program to check whether a given number is palindrome or not: 

 ------------------------------------------------------------------

Input a number: 12344321

12344321 is a Palindrome Number.