Sukumar Paul – Linux Hint https://linuxhint.com Exploring and Master Linux Ecosystem Sun, 28 Feb 2021 23:14:40 +0000 en-US hourly 1 https://wordpress.org/?v=5.6.2 C++ Friend Function https://linuxhint.com/c-friend-function/ Fri, 26 Feb 2021 18:49:47 +0000 https://linuxhint.com/?p=91929 A function is a block of code that performs a certain task and provides the output. It is mainly used to eliminate repetitive code. In this tutorial, we will look into the friend function in C++ and explain its concept with working examples.

What is Friend Function?

Friend function is a non-member function that can access the private and protected members of a class. “Friend” is a keyword used to indicate that a function is the friend of a class. This allows the compiler to know that the particular function is a friend of the given class. The friend function then should be able to access the private and protected member of a given class. Without the friend keyword, a non-member outside function can only access the public members of a class.

Key Features of Friend Function:

Here are the key features of the friend function:

  1. A friend function is not in the scope of the class.
  2. The friend function cannot be invoked using an instance of a class.
  3. It can access the members using the object and dot operator.

Syntax of Friend Function:

Here is the syntax of the friend function:

class Class_Name_Demo
{
   ………………………………………
   ………………………………………

    friend return_Type function_Name(arg_1, arg_2,);
};

Example of Friend Function:

Now, let us look into an example program to understand the concept of the friend function in C++. In the below example program, we have the “Friend_Demo” class. It has three different types of data members, i.e., private, protected, and public.

We have defined another function, i.e., “friendDemo_Func()” outside the scope of the “Friend_Demo” class and tried to access the members (private, protected, and public) of the “Friend_Demo” class.

But, as you can see in the output below when we compile the program, it throws compilation errors. The friend function is going to exactly solve this problem.

#include <iostream>
using namespace std;

class Friend_Demo
{
   private:
    int i_private;
   protected:
    int i_protected;
   public:
    int i_public;
};

void friendDemo_Func()
{
    Friend_Demo fd;
   
    fd.i_private    = 10;
    fd.i_protected  = 15;
    fd.i_public     = 20;
   
    cout << fd.i_private << endl;
    cout << fd.i_protected << endl;
    cout << fd.i_public << endl;
}

int main()
{
    friendDemo_Func();

    return 0;
}

In the previous program, we were getting compilation errors while trying to access the private, protected, and public members of a class from a non-member function. This is because a non-member function is not allowed to access the private and protected members of a class from outside the scope of the class.

Now, in this example, we have declared “friendDemo_Func()” function as a friend inside the scope of the class, i.e., “Friend_Demo”:

friend void friendDemo_Func();

We have created an object, i.e., “fd” of the “Friend_Demo” class inside the “friendDemo_Func()” function. Now, we can access the private, protected, and public members of the “Friend_Demo” class using the dot operator. We have assigned 10, 15, and 20 to i_private, i_protected, and i_public, respectively.

As you can see in the output below, this program is now compiled and executed without any errors and print the output as expected.

#include <iostream>
using namespace std;

class Friend_Demo
{
   private:
    int i_private;
   protected:
    int i_protected;
   public:
    int i_public;
    friend void friendDemo_Func();
};

void friendDemo_Func()
{
    Friend_Demo fd;
   
    fd.i_private    = 10;
    fd.i_protected  = 15;
    fd.i_public = 20;
   
    cout << fd.i_private << endl;
    cout << fd.i_protected << endl;
    cout << fd.i_public << endl;
}

int main()
{
    friendDemo_Func();

    return 0;
}

Conclusion:

In this article, I have explained the concept of the friend function in C++. I have also shown two working examples to explain how the friend function behaves in C++. Sometimes, the friend function can be very useful in a complex programming environment. However, a programmer should be cautious about overusing it and compromising its OOP features. ]]> Python Date and Time Module https://linuxhint.com/python-date-time-module/ Sat, 30 Jan 2021 11:28:53 +0000 https://linuxhint.com/?p=88162 In this article, we are going to discuss the Python Date and Time module. Python does not have its data type to represent a date, but it allows the programmer to import a DateTime module. In addition to the date, time can also be displayed by Python in various ways. With the assistance of date and time modules, it is possible to set the Python time and date.

Content of Date Time Module

The data and time can be used in Python by importing the DateTime module. We can import the DateTime module by simply using the import statement as follows:

import datetime

Once the datetime module is imported, we can use the classes, methods, and constants available in the datetime module.

With the dir() function, we can get a list that comprises attributes of the datetime module.

print(dir(datetime))

Commonly used classes in the DateTime module:

Python language uses different types of date, time, and DateTime classes for different functions for representing the date, time, and time intervals.

Here are the commonly used classes in the datetime module:

date Class: This class is used to manipulate the form of the month, year, and day.

time Class: Time does not depend on the day and is represented in an hour, minute, second, and microsecond.

dateTime Class: This is a combination of both classes’ date and time. Therefore it is represented in the form of the month, day, year, hour, minute, second, and microsecond.

timedelta Class: Timedelta class is used to calculate the duration, which shows the differences between two dates, time, and DateTime. The differences can be obtained in microsecond resolution.

How to get the current date and time?

Now, let’s look into a simple example to get the current date and time in python.

import datetime
datetime_object = datetime.datetime.now()
print(datetime_object)

First, we import the datetime module by using the import statement and then creating the datetime object. The datetime objects can be used in Python to check the current date and time, representing today’s date and the current time in the form of year, month, days, hours, minutes, and seconds. After executing this code, the present date and time will be displayed as the output.

How to get the current date?

Now, in the following example, we will see how just to get the current date using the datetime module. Let’s look into the following example code:

from datetime import date
CurrentDate= date.today()
print("Today =", CurrentDate)

We have imported the date from the datetime module and then created an object, i.e., CurrentDate, and printed the CurrentDate.

How to get the current time?

In the previous example, we have seen how to get the current date. In this example, we will see how to get the current time.

import time
localtime = time.localtime(time.time())
print("Local current time :", localtime)

It is the best way to translate the instant time, which is based on seconds. The epoch floating-point value needs to be converted into the time tuple, bypassing through floating-point value to a function which is known as local time, and as you return, the time table will be got with valid 9 items. This is not the formatted one; to get the formatted time, asctime() can be used.

How to get the date from the timestamp?

The timestamp is considered as a database where the date and time can be stored; it can also store the datetime object.

from datetime import date
timestamp = date.fromtimestamp(1611474364)
print("Date =", timestamp)

To get the current date and time, it is possible to create a date object from the timestamp. A UNIX timestamp consists of a number of seconds between a specific date and January 1, 1970, at UTC. It is possible to convert timestamp to date by using the method fromtimestamp().

Calculate the difference between two date and times

Now, let’s look into an example to determine the difference between the two dates and times.

import datetime
from datetime import timedelta

my_datetimeFormat = '%Y-%m-%d %H:%M:%S.%f'
my_d1 = '2019-02-25 4:01:29.442'
my_d2 = '2021-01-24 08:36:49.047'
my_diff = datetime.datetime.strptime(my_d1, my_datetimeFormat) \
           - datetime.datetime.strptime(my_d2, my_datetimeFormat)

print("Difference:", my_diff)
print("Days:", my_diff.days)
print("Microseconds:", my_diff.microseconds)
print("Seconds:", my_diff.seconds)

In terms of finding out the differences between two dates with python’s help, the user can use the timedelta class. It is available in the datetime library. This class accumulates the differences between the two dates. The differences between two dates can find out by two different date objects. In this case, let’s suppose two date objects are date 1 and date 2. The difference between two date objects can be represented in the form of minutes and the seconds of the timedelta object.

Format Date Time using strftime()

We can format date and time using the strftime() method. Here is an example:

import datetime

z = datetime.datetime(2021, 1, 24)

print("Fullname of Month: ",z.strftime("%B"))
print("Short Name of Month: ", z.strftime("%b"))
print("Numeric value of Month: ", z.strftime("%m"))

print("\nDay: ", z.strftime("%d"))
print("Week Day: ", z.strftime("%A"))
print("Week Day: ", z.strftime("%a"))

The purpose of using a date-time object is to convert data objects into readable strings by using a particular method. This method is known as strftime(). It needs one parameter and format for formatting the returned string.

Conclusion

The datetime module is a very helpful module in python to manipulate date, time. In this article, we have discussed the commonly used classes, objects, methods. We have also looked into several examples and the outputs to understand the basic concept of the datetime module.

]]>
C++ Operator Overloading https://linuxhint.com/cpp-operator-overloading/ Tue, 19 Jan 2021 09:52:17 +0000 https://linuxhint.com/?p=86589 This article provides a guide to operator overloading in C++. Operator overloading is a useful and powerful feature of the C++ programming language. C++ allows overloading of most built-in operators. In this tutorial, we will use several examples to demonstrate the operator overloading mechanism.

What is Operator?

An operator is a symbol that indicates to the compiler to perform a particular operation. For example, there are various types of operators in C++, such as Arithmetic Operators, Logical Operators, Relational Operators, Assignment Operators, Bitwise Operators, and more.

What is Operator Overloading?

The C++ language allows programmers to give special meanings to operators. This means that you can redefine the operator for user-defined data types in C++. For example, “+” is used to add built-in data types, such as int, float, etc. To add two types of user-defined data, it is necessary to overload the “+” operator.

Syntax for Operator Overloading

C++ provides a special function called “operator” for operator overloading. The following is the syntax for operator overloading:

class sampleClass
{
    ..............
    Public:
       returnType operator symbol (arguments) {
           ..............
       }
     ..............
};

Here, “operator” is a keyword, and “symbol” is the operator that we want to overload.

Examples

Now that you understand the overall concept of operator overloading, let us go through a couple of working example programs for you to understand this idea more concretely. We will cover the following examples:

  1. Example 1: Unary Operator Overloading (1)
  2. Example 2: Unary Operator Overloading (2)
  3. Example 3: Binary Operator Overloading
  4. Example 4: Relational Operator Overloading

Example 1: Unary Operator Overloading (1)

In this example, we will demonstrate how a unary operator can be overloaded in C++. We have defined the class, “Square_Box,” and the public functions, “operator ++ ()” and “operator ++ (int),” to overload both the prefix and the postfix increment operators. In the “main()” function, we have created the object, “mySquare_Box1.” We have then applied the prefix and postfix increment operators to the “mySquare_Box1” object to demonstrate the unary operator overloading.

#include <iostream>
using namespace std;

class Square_Box
{
   private:
    float length;
    float width;
    float height;

   public:
    Square_Box() {}
    Square_Box(float l, float w, float h)
    {
        length = l;
        width = w;
        height = h;
    }

    // Operator Overloading  - "++" prefix operator
    void operator ++ ()
    {
        length++;
        width++;
        height++;
    }

    // Operator Overloading  - "++" postfix operator
    void operator ++ (int)
    {
        length++;
        width++;
        height++;
    }

    void output()
    {
        cout << "\tLength = " << length << endl;
        cout << "\tWidth = " << width << endl;
        cout << "\tHeight = " << height << endl;
        cout << endl;
    }
};

int main()
{
    Square_Box mySquare_Box1(3.0, 5.0, 6.0);

    cout << "Dimensions of mySquare_Box1 = " << endl;
    mySquare_Box1.output();
   
    mySquare_Box1++;
   
    cout << "Dimensions of mySquare_Box1 = " << endl;
    mySquare_Box1.output();
   
    ++mySquare_Box1;
   
    cout << "Dimensions of mySquare_Box1 = " << endl;
    mySquare_Box1.output();    

    return 0;
}

Example 2: Unary Operator Overloading (2)

This is another example in which we will demonstrate how a unary operator can be overloaded in C++. We have defined the class, “Square_Box,” and the public functions, “operator — ()” and “operator — (int),” to overload both the prefix and postfix decrement operators. In the “main()” function, we have created the “mySquare_Box1” object. We have then applied the prefix and postfix decrement operators to the “mySquare_Box1” object.

#include <iostream>
using namespace std;

class Square_Box
{
   private:
    float length;
    float width;
    float height;

   public:
    Square_Box() {}
    Square_Box(float l, float w, float h)
    {
        length = l;
        width = w;
        height = h;
    }

    // Operator Overloading  - "--" prefix operator
    void operator -- ()
    {
        length--;
        width--;
        height--;
    }

    // Operator Overloading  - "--" postfix operator
    void operator -- (int)
    {
        length--;
        width--;
        height--;
    }

    void output()
    {
        cout << "\tLength = " << length << endl;
        cout << "\tWidth = " << width << endl;
        cout << "\tHeight = " << height << endl;
        cout << endl;
    }
};

int main()
{
    Square_Box mySquare_Box1(3.0, 5.0, 6.0);

    cout << "Dimensions of mySquare_Box1 = " << endl;
    mySquare_Box1.output();
   
    mySquare_Box1--;
   
    cout << "Dimensions of mySquare_Box1 = " << endl;
    mySquare_Box1.output();
   
    --mySquare_Box1;
   
    cout << "Dimensions of mySquare_Box1 = " << endl;
    mySquare_Box1.output();    

    return 0;
}

Example 3: Binary Operator Overloading

Now, we will look at an example of binary operator overloading. The syntax for binary operator overloading will be somewhat different from unary operator overloading. In this example, we will overload the “+” operator to add two “Square_Box” objects.

#include <iostream>
using namespace std;

class Square_Box
{
   private:
    float length;
    float width;
    float height;

   public:
    Square_Box() {}
    Square_Box(float l, float w, float h)
    {
        length = l;
        width = w;
        height = h;
    }

    // Operator Overloading  - "+" operator
    Square_Box operator + (const Square_Box& obj)
    {
        Square_Box temp;
        temp.length = length + obj.length;
        temp.width = width + obj.width;
        temp.height = height + obj.height;
        return temp;
    }

    void output()
    {
        cout << "\tLength = " << length << endl;
        cout << "\tWidth = " << width << endl;
        cout << "\tHeight = " << height << endl;
        cout << endl;
    }
};

int main()
{
    Square_Box mySquare_Box1(3.0, 5.0, 6.0), mySquare_Box2(2.0, 3.0, 5.0), result;

    cout << "Dimensions of mySquare_Box1 = " << endl;
    mySquare_Box1.output();

    cout << "Dimensions of mySquare_Box2 = " << endl;
    mySquare_Box2.output();
   
    result = mySquare_Box1 + mySquare_Box2;
   
    cout << "Dimensions of resultant square box = " << endl;
    result.output();

    return 0;
}

Example 4: Relational Operator Overloading

Now, we will look at an example of relational operator overloading. The syntax for relational operator overloading is just like that of the binary operator overloading. In this example, we will overload the “<” and “>” operators to apply to the “Square_Box” objects.

#include <iostream>
using namespace std;

class Square_Box
{
   private:
    float length;
    float width;
    float height;

   public:
    Square_Box() {}
    Square_Box(float l, float w, float h)
    {
        length = l;
        width = w;
        height = h;
    }

    // Operator Overloading  - "<" operator
    bool operator < (const Square_Box& obj)
    {
        if(length < obj.length)
            return true;
        else
            return false;
    }

   
    // Operator Overloading  - ">" operator
    bool operator > (const Square_Box& obj)
    {
        if(length > obj.length)
            return true;
        else
            return false;
    }
    void output()
    {
        cout << "\tLength = " << length << endl;
        cout << "\tWidth = " << width << endl;
        cout << "\tHeight = " << height << endl;
        cout << endl;
    }
};

int main()
{
    Square_Box mySquare_Box1(2.0, 3.0, 5.0), mySquare_Box2(4.0, 6.0, 8.0);
    bool result;

    cout << "Dimensions of mySquare_Box1 = " << endl;
    mySquare_Box1.output();

    cout << "Dimensions of mySquare_Box2 = " << endl;
    mySquare_Box2.output();
   
    result = mySquare_Box1 < mySquare_Box2;
    cout << "mySquare_Box1 < mySquare_Box2 = " << result < mySquare_Box2;
    cout < mySquare_Box2 = " << result << endl;    

    return 0;
}

Conclusion

C++ is a general-purpose and flexible programming language that is widely used in a variety of domains. This programming language supports both compile-time and run-time polymorphism. This article showed you how to perform operator overloading in C++. This is a very useful feature of C++ that adds some extra effort for the developer to define the operator for overloading, but it definitely makes life easier for the user of the class. ]]> C++ Call By Address and Call By Reference https://linuxhint.com/call-by-address-and-call-by-reference-cpp/ Mon, 28 Dec 2020 04:30:00 +0000 https://linuxhint.com/?p=83225

C++ is a flexible general-purpose programming language. It was originally created by Bjarne Stroustrup, a Danish computer scientist, back in 1985. C++ supports three-parameter passing methods, i.e., call by value, call by address, and call by reference. In this article, we are going to discuss about call by address and call by reference mechanism.

What is a function?

Before we jump into the actual topic, we need to understand what the function is in C++. Many of you may already be familiar with functions.

A function is basically a piece of code that can be used to perform a certain task. A function is mainly used to reduce the repetitive code in a C++ program. It takes input as parameters and returns the output as a return value. If we define the function once, we can call/use it multiple times in the later part of our program. That way, we save a lot of repetitive code in the program.

Every C++ program shall have the “main()” function. The “main()” function is the entry point for a C++ program. Apart from the “main()” function, the programmer can define as many functions as they want.

Here is the syntax of defining a function:

Return_type Function_Name (Input parameter List)

Function in C++ can accept 0 or more number of input parameters, whereas it can return only one return-value.

What is Address?

There are two types of variables in C++ (similar to C language) – Data Variable and Address Variable. The address variable is used to store the address of another data variable. For example, let’s consider the following code snippet:

int i = 100;
int *ptr = &i;

Here, the first statement tells us that the variable “i” is a data variable, and it is storing the value 100. In the second statement, we are declaring a pointer variable, i.e. “ptr,” and initializing it with the address of the variable “i”.

What is Reference?

The reference is another powerful feature of C++ language. Let’s consider the following code snippet:

int a = 200;
int &r = a;

In this example, we have declared an integer, i.e. “a” and then declared a reference variable “r”, which is initialized with the value of “a”. So, the reference variable is nothing but an alias of another variable.

Parameter passing methods:

There are three types of parameter passing methods in C++ language:

  1. Call by value / Pass by value
  2. Call by address / Pass by address
  3. Call by reference / Pass by reference

In this article, we are discussing about the – Call by address and Call by reference.

What is Call By Address / Pass by address?

In the case of the Call by address / Pass by address method, the function arguments are passed as address. The caller function passes the address of the parameters. Pointer variables are used in the function definition. With the help of the Call by address method, the function can access the actual parameters and modify them. We will see an example of the Call by address method later section of this article.

What is Call By Reference / Pass by reference?

In the Call by reference / Pass by reference method, the function parameters are passed as a reference. Inside the function definition, the actual parameters are accessed using the reference variable.

Examples:

Now, since we understand the concept of parameter passing methods, we will see several example programs to understand the parameter passing mechanism in C++:

  1. Example-1 – Call by Address (1)
  2. Example-2 – Call by Address (2)
  3. Example-3 – Call by Reference (1)
  4. Example-4 – Call by Reference (2)

The first two examples are given to explain how the Call by address method works in C++. The last two examples are to explain the Call by reference concept.

Example-1 – Call by Address (1)

In this example, we are going to demonstrate the call by address mechanism. From the “main()” function, we are calling the “hello()” function and passing the address of “var”. In the function definition, we are receiving the address of “var” in a pointer variable, i.e., “p”. Inside the function hello, the value of “var” is being changed to 200 with the help of the pointer. Therefore, the value of “var” is getting changed to 200 inside the “main()” function after the “hello()” function call.

#include <iostream>
using namespace std;

void hello(int *p)
{
    cout << endl << "Inside hello() function : " << endl;
    cout << "Value of *p = " << *p << endl;
    *p = 200;
    cout << "Value of *p = " << *p << endl;
    cout << "Exiting hello() function." << endl;
}

int main()
{
    int var = 100;
    cout << "Value of var inside main() function = " << var << endl;
   
    hello(&var);
   
    cout << endl << "Value of var inside main() function = " << var << endl;
   
    return 0;
}

Example-2 – Call by Address (2)

This is another example of the call by address method. In this example, we are going to explain how the call by address method can be used to solve a real-life problem. For example, we want to write a function to swap two variables. If we use the call by value mechanism to swap two variables, the actual variables do not get swapped in the caller function. The call by address method can be used in such a scenario. In this example, we are passing the address of both var_1 (&var_1) and var_2 (&var_2) to “mySwap()” function. Inside the “mySwap()” function, we are swapping the values of these two variables with the help of the pointers. As you can see in the below output, the actual value of these variables is getting swapped in the “main()” function after the “mySwap()” function is executed.

#include <iostream>
using namespace std;

void mySwap(int *vptr_1, int *vptr_2)
{
   int temp_var;
   temp_var = *vptr_1;
   *vptr_1 = *vptr_2;
   *vptr_2 = temp_var;
}

int main()
{
    int var_1 = 100;
    int var_2 = 300;
   
    cout << "Before calling mySwap() function, value of var_1 : " << var_1 << endl;
    cout << "Before calling mySwap() function, value of var_2 : " << var_2 << endl << endl;
       
    cout << "Calling mySwap() function - Call by address." << endl << endl;
    mySwap(&var_1, &var_2);
   
    cout << "After calling mySwap() function, value of var_1 : " << var_1 << endl;
    cout << "After calling mySwap() function, value of var_2 : " << var_2 << endl;
   
    return 0;
}

Example-3 – Call by Reference (1)

In this example, we are going to demonstrate how call by reference works in C++. In the “hello()” function definition, the value is being received as a reference variable (&p). With the help of the reference variable (i.e., p), we are able to change the value of the actual parameter (var) inside the “main()” function.

#include <iostream>
using namespace std;

void hello(int &p)
{
    cout << endl << "Inside hello() function : " << endl;
    cout << "Value of p = " << p << endl;
    p = 200;
    cout << "Value of p = " << p << endl;
    cout << "Exiting hello() function." << endl;
}

int main()
{
    int var = 100;
    cout << "Value of var inside main() function = " << var << endl;
   
    hello(var);
   
    cout << endl << "Value of var inside main() function = " << var << endl;
   
    return 0;
}

Example-4 – Call by Reference(2)

This is another example of a call by reference. In this example, we are going to demonstrate how call by reference works in C++ with the help of a real-world example. The “mySwap()” function is called from the “main()” function with the following parameters – var_1 and var_2. Inside the “mySwap()” function, we are receiving the parameters as reference variables.

#include <iostream>
using namespace std;

void mySwap(int &vref_1, int &vref_2)
{
   int temp_var;
   temp_var = vref_1;
   vref_1 = vref_2;
   vref_2 = temp_var;
}

int main()
{
    int var_1 = 100;
    int var_2 = 300;
   
    cout << "Before calling mySwap() function, value of var_1 : " << var_1 << endl;
    cout << "Before calling mySwap() function, value of var_2 : " << var_2 << endl << endl;
       
    cout << "Calling mySwap() function - Call by reference." << endl << endl;
    mySwap(var_1, var_2);
   
    cout << "After calling mySwap() function, value of var_1 : " << var_1 << endl;
    cout << "After calling mySwap() function, value of var_2 : " << var_2 << endl;
   
    return 0;
}

Conclusion

Understanding the parameter passing methods in C++ is very crucial. The C programming language supports the Call by value and Call by address only. But, C++ supports Call by reference along with the previous two mechanisms. In this article, we have seen several working examples to understand the concept of Call by address and Call by reference. Call by address is a very powerful and popular method in embedded domain applications. ]]> C++ Function Overloading https://linuxhint.com/c_function_overloading/ Tue, 08 Dec 2020 01:24:50 +0000 https://linuxhint.com/?p=79925

C++ is a flexible general-purpose programming language. This programming language was originally created by Bjarne Stroustrup, a Danish computer scientist, back in 1985. C++ supports polymorphism, inheritance, and more. This article covers function overloading to achieve compile-time polymorphism in the C++ programming language.

What is a Function?

A function is nothing more than a specific piece of code that performs a specific task based on inputs provided, and it returns the requested results to the user in the form of an output. Functions are used to eliminate repetitive code in large codebases.

After defining a function, you can reuse it at a later point in time, either in the same program or in a different program.

Function Syntax

A function in C++ has the following syntax:

returnType functionName(parameter_list)

{

        …………………

        …………………

        return return_value;

}

The returnType, parameter_list, and return statement are optional. A function in C++ can return a maximum of one value. If a function does not return any value, the returnType should be defined as void.

What is Function Overloading?

In C++, multiple function definitions can have the same function name, but with different parameters. This is called function overloading. With the help of the function overloading feature, compile-time polymorphism can be achieved in C++.

Functions can be overloaded in the following ways:

  1. The number of parameters can be different
  2. The data type of the parameters can be different
  3. The sequence of the parameters can be different

However, the return value is not considered for function overloading. 

The following functions are overloaded:

  1. int addition (int a, int b)
  2. float addition (float f, gloat g)
  3. float addition (float f, int i)
  4. float addition (int i, float f)
  5. int addition (int a, int b, int c)
  6. float addition (float f, float g, float h)

As you can see, with the help of the function overloading feature in C++, there can be multiple definitions/functionalities with the same function name and in the same scope.

Without the function overloading feature, you would need to write a separate function [for example, addition_1(), addition_2() etc] for each variation. For example, you may have to write addition_1() to add two integers, addition_2() to add two floats, and so on. However, as you can see above, the function overloading feature can be used to define multiple variations of the “addition()” function while still keeping the same function name.

The following functions are not considered to be overloaded because the only difference between these two is the return type (return type is not considered for function overloading in C++):

  1. int addition (int a, int b)
  2. float addition (int a, int b)

Examples

Now that you understand the concept of function overloading, we will go through a couple of working example programs to understand this concept more clearly. We will cover the following examples:

  1. Example 1: Simple Function
  2. Example 2: Simple Addition Function
  3. Example 3: Function Overload (1)
  4. Example 4: Function Overload (2)
  5. Example 5: Function Overload (3)

The first two examples explain how normal functions work in C++, while the last three examples demonstrate the function overloading feature in C++.

Example 1: Simple Function

In this example, we will demonstrate how a simple function can be defined and called in C++. We will define a class called “Display” and a public function called “display().” From the “main()” function, we will call the “display()” function with the help of the “Display” class object (d).

#include <iostream>


using namespace std;


class Display

{

public:

        void display()

        {

                cout << "Hello World!" << endl;

        }

};


int main()

{

        Display d;

        d.display();

        return 0;

}

Example 2: Simple Addition Function

In this example, we will demonstrate how to define a simple “addition()” function in C++. We will define a class called “DemoAdd” and a public function called “addition().” From the “main()” function, we will call the “addition()” function with the help of the “DemoAdd” class object (d).

In this example, the current implementation of the “addition()” function accepts only two integer parameters. That means that the current “addition()” function is capable of adding only two integers.

To add three integers instead of two, a function with a different name, such as “addition_1(),” can be defined. In C++, a function can be overloaded, meaning that another definition of the “addition()” function can be defined to add three integers and keep the same name, i.e., “addition().” In the next example, we will look at how to overload the “addition()” function.

#include <iostream>


using namespace std;


class DemoAdd

{

public:

        int addition(int a, int b)

        {

                int result;

                result = a + b;

       

                return result;

        }

};



int main()

{        

        DemoAdd d;

       

        int i1 = 10, i2 = 20, res;

        res = d.addition(i1, i2);

       

        cout << "Result = " << res << endl;

       

        return 0;

}

Example 3: Function Overload (1)

In the previous example, we defined the “addition()” function to add two integers and return the computed result. Now, in this example, we will overload the “addition()” function to add three integers. So, we will be able to call the “addition()” function with two integer arguments, as well as three integer arguments.

Without the function overloading feature, we would have to write another function with a different name.

#include <iostream>


using namespace std;


class DemoAdd

{

public:

        // First function definition of addition()

        int addition(int a, int b)

        {

                int result;

                result = a + b;

       

                return result;

        }


        // Overloaded version of addition() function

        int addition(int a, int b, int c)

        {

                int result;

                result = a + b + c;

       

                return result;

        }

};


int main()

{        

        DemoAdd d;

         int i1 = 10, i2 = 20, i3 = 30, res1, res2;

       

        res1 = d.addition(i1, i2);     // addition() with 2 parameters

        res2 = d.addition(i1, i2, i3); // addition() with 3 parameters

       

        cout << "Result = " << res1 << endl;

        cout << "Result = " << res2 << endl;

       

        return 0;

}

Example 4: Function Overload (2)

In earlier sections of this article, you learned that function overloading can be performed based on differences in parameter type. Here, we have overloaded the “addition()” function based on the parameter’s data type. In the first version of the addition function, we will add two integer type variables; and in the second version, we will add two float type variables.

#include <iostream>


using namespace std;


class DemoAdd

{

public:

        // First definition of addition()

        int addition(int a, int b)

        {

                int result;

                result = a + b;

       

                return result;

        }


        // Overloaded function definition

        float addition(float f, float g)

        {

                float result;

                result = f + g;

       

                return result;

        }

};


int main()

{        

        DemoAdd d;

         int i1 = 10, i2 = 20, res1;

        float f1 = 10.5, f2 = 20.7, res2;

       

        res1 = d.addition(i1, i2);  // addition(int a, int b) will be called

        res2 = d.addition(f1, f2);  // addition(float f, flat g) will be called

       

        cout << "Result = " << res1 << endl;

        cout << "Result = " << res2 << endl;

       

        return 0;

}

Example 5: Function Overload (3)

In this example, the “addition()” function is overloaded based on differences in the sequence of the parameter list. This is another way to overload a function in C++.

#include <iostream>


using namespace std;


class DemoAdd

{

public:

        // First function definition of addition() function

        float addition(int a, float b)

        {

                float result;

                result = (float)a + b;

       

                return result;

        }


        // Overloaded function definition of addition() function

        float addition(float a, int b)

        {

                float result;

                result = a + (float)b;

       

                return result;

        }

};


int main()

{        

        DemoAdd d;

         int i1 = 10;

        float f1 = 10.5, res1, res2;

       

        res1 = d.addition(i1, f1); // addition(int a, float b) will be called

        res2 = d.addition(f1, i1); // addition(float a, int b) will be called

       

        cout << "Result = " << res1 << endl;

        cout << "Result = " << res2 << endl;

       

        return 0;

}

Conclusion

C++ is a general-purpose and flexible programming language that is widely used in various domains. This programming language supports both compile-time and run-time polymorphism. In this article, you learned how to achieve compile-time polymorphism in C++ using the function overloading feature. This is a very helpful feature in C++ that helps programmers to write readable code. It can also be helpful for writing reusable code.

]]>
How to parse JSON in C++ https://linuxhint.com/parse-json-data-c/ Thu, 03 Dec 2020 19:05:41 +0000 https://linuxhint.com/?p=79284 The intention of this tutorial is to understand the JSON data and how to parse JSON data in C++. We will discuss JSON data, Object, Array, JSON syntax, and then go through several working examples to understand the parsing mechanism of JSON data in C++.

What is JSON?

JSON is a light-weight text-based representation for storing and transferring structured data in an organized way. The JSON data is represented in the form of ordered lists and key-value pairs. JSON stands for JavaScript Object Notation. As the full name indicates, it is derived from JavaScript. However, JSON data is supported in most of the popular programming languages.

It is often used to transfer the data from the server to a web page. It is much easier and cleaner to represent the structured data in JSON than XML.

JSON Syntax Rule

Here are the JSON syntax rules:

  1. JSON Data should always be in the form of key-value pairs.
  2. JSON Data is separated by commas.
  3. A Curly brace is used to represent JSON Object.
  4. A square bracket is used to represent a JSON Array.

What is JSON Data?

The JSON data is represented in the form of key-value pairs. This is similar to a dictionary or hash in other programming languages.

“Name” : ”Drake”

This is an example of simple JSON data. The key here is “Name” and “Drake” is the corresponding value. The key, i.e., “Name” and the value, i.e., “Drake” are separated by a colon.

JSON File Extension

The JSON data is normally stored in the file with the extension of “.json”. For example, to store the employee’s data, you can simply name the file as ‘employee.json’. This would be a simple text file. You can then open this JSON file in any of your favorite text editors.

JSON Object

The JSON object is nothing but the JSON data enclosed within the curly braces. Here is a sample JSON object:

{
   “Name”: ”Drake”,
   “Employee ID”: “23547a”,
    “Phone”:23547,
    “Department”: “Finance”
 }

A JSON object can contain multiple JSON data. Each JSON data is separated by a comma. JSON data is represented as key-value pairs. The key, i.e., “Name” and the value, i.e., “Drake” are separated by a colon. In the above example, there are four key-value pairs. The first key is “Name”; “Drake” is the corresponding value for it. Similarly, “EmployeeID”, “Phone”, and “Department” are the other three keys.

JSON Array

A JSON array can contain several comma-separated JSON objects. The JSON array is enclosed within a square bracket. Let’s look at an example of a JSON array:

"Students":[
    {"firstName":"Sean", "lastName":"Brown"},
    {"firstName":"Drake", "lastName":"Williams"},
    {"firstName":"Tom", "lastName":"Miller"},
    {“firstName”:”Peter”, “lastName”: “Johnson”}
]

This is an example of a JSON array. Here, “Students” is enclosed with a square bracket, i.e., array, and it contains four JSON objects. Each of these objects is represented in the form of key-value pairs and is separated by a comma.

A Sample JSON File

Now, since we understood JSON data, JSON objects, JSON array, let’s look at an example of a JSON file:

{
  “firstName”: “Sean”,
  “lastName”: “Brown”,
  “Student ID”: 21453,
  “Department”: “Computer Sc.”,
  “Subjects”:[“Math”, “Phy”, “Chem”]
    }

Parsing Libraries in C++:

There is no native solution for parsing JSON data in C++. However, there are several libraries to parse JSON data in C++. In this article, we are going to look into the two most popular libraries to parse JSON data in C++. Here are the GitHub links for parsing JSON data:

  1. https://github.com/nlohmann/json
  2. https://github.com/Tencent/rapidjson/

You may want to download these libraries to be able to execute the examples shown below.

Examples

Now, we have a basic understanding of JSON data, objects, arrays, and available parsing libraries. Let’s now look at a couple of examples to parse JSON data in C++:

  • Example-1: Parse JSON in C++
  • Example-2: Parse and Serialize JSON in C++
  • Example-3: Parse JSON in C++

For Example-1 and Example-2, we are going to make use of the “nlohmann” library. In the case of Example-3, we will use the “RapidJSON” library.

Example-1: Parse JSON in C++

In this example program, we will demonstrate how to access values of JSON data in C++.

#include <iostream>
#include "json.hpp"

using json = nlohmann::json;

int main()
{

    // jdEmployees
    json jdEmployees =
    {
        {"firstName","Sean"},
        {"lastName","Brown"},
        {"StudentID",21453},
        {"Department","Computer Sc."}
    };

    // Access the values
    std::string fName = jdEmployees.value("firstName", "oops");
    std::string lName = jdEmployees.value("lastName", "oops");
    int sID = jdEmployees.value("StudentID", 0);
    std::string dept = jdEmployees.value("Department", "oops");
   
    // Print the values
    std::cout << "First Name: " << fName << std::endl;
    std::cout << "Last Name: " << lName << std::endl;
    std::cout << "Student ID: " << sID << std::endl;
    std::cout << "Department: " << dept << std::endl;
             
    return 0;
}

Example-2: Parse and Serialize JSON in C++

In this example program, we are going to see how to parse and serialize JSON in C++. We are using “json::parse()” to parse the JSON data.

#include <iostream>
#include "json.hpp"
#include <iomanip>

using json = nlohmann::json;

int main()
{
    // Here is a JSON text
    char text[] = R"(
    {
        "
Book": {
            "
Width":  450,
            "
Height": 30,
            "
Title":  "Hello World",
            "
isBiography": false,
            "
NumOfCopies": 4,
            "
LibraryIDs": [2319, 1406, 3854, 987]
        }
    }
    )"
;

    // Let's parse and serialize JSON
    json j_complete = json::parse(text);
    std::cout << std::setw(4) << j_complete << std::endl;
}

Example-3: Parse JSON in C++

Now, we will demonstrate how to parse JSON string using the RapidJSON library. RapidJSON was originally inspired by the RapidXML. In this example program, we are parsing a JSON string into DOM. We have declared “mydoc” of type “Document” and then using the “mydoc.parse()” method to parse the JSON string.

#include <iostream>
#include "rapidjson/writer.h"
#include "rapidjson/document.h"
#include "rapidjson/stringbuffer.h"

using namespace rapidjson;

int main()
{

  const char* json = "{"firstName":"Sean","lastName":"Brown","empId":21453,
  "
department":"Computer Sc."}";

  // Parse the JSON string into DOM
  Document mydoc;
  mydoc.Parse(json);

  // DOM to string
  StringBuffer buffer;
  Writer<StringBuffer> writer(buffer);

  mydoc.Accept(writer);

  // Print the output
  std::cout << buffer.GetString() << std::endl;

  return 0;
}

Conclusion

In this article, we have briefly discussed JSON data, object, array, and syntax. As we know, there is no native solution for JSON data parsing in C++; we have used two different libraries to parse JSON data in C++. We looked into three different examples to demonstrate the JSON data parsing mechanism in C++. As compared to the “nlohmann” library, the RapidJSON is small, fast, and memory-friendly. ]]> How to Parse XML in C++ https://linuxhint.com/parse_xml_in_c__/ Fri, 20 Nov 2020 20:25:09 +0000 https://linuxhint.com/?p=77607

In this article, we are going to discuss how to parse XML in C++ programming language. We will see several working examples to understand the XML parsing mechanism in C++.

What is XML?

XML is a markup language and is mainly used for storing and transferring data in an organized way. XML stands for eXtensible Markup Language. It is very similar to HTML. The XML is completely focused on storing and transferring the data, whereas the HTML is used for displaying the data on the browser.

A Sample XML File/XML Syntax

Here is a sample XML file:

<?xml version="1.0" encoding="utf-8"?>

<EmployeeData>

    <Employee student_type="Part-time">

        <Name>Tom</Name>

    </Employee>

    <Employee student_type="Full-time">

        <Name>Drake</Name>

    </Employee>

</EmployeeData>

Unlike HTML, It is a tag-oriented markup language, and we can define our own tag in an XML file. In the above example, we have several user-defined tags such as “<Employee>”. Every tag will have the corresponding ending tag. “</Employee>” is the ending tag for “<Employee>”. We can define as many user-defined tags as we want to organize the data.

Parsing Libraries in C++:

There are various libraries to parse XML data in most of the high-level programming languages. C++ is not an exception. Here are the most popular C++ libraries to parse XML data:

  1. RapidXML
  2. PugiXML
  3. TinyXML

As the name suggests, the RapidXML is mainly focused on speed, and it is a DOM style parsing library. PugiXML supports Unicode conversion. You may want to use PugiXML if you want to convert UTF-16 doc to UTF-8. TinyXML is a bare-minimum version to parse XML data and not that fast as compared to the previous two. If you want to just get the job done and don’t care about the speed, you can choose TinyXML.

Examples
Now, we have a basic understanding of XML and XML parsing libraries in C++. Let’s now look at a couple of examples to parse xml file in C++:

  • Example-1: Parse XML in C++ using RapidXML
  • Example-2: Parse XML in C++ using PugiXML
  • Example-3: Parse XML in C++ using TinyXML

In each of these examples, we will use the respective libraries to parse a sample XML file.

Example-1: Parse XML in C++ using RapidXML

In this example program, we will demonstrate how to parse xml using RapidXML library in C++. Here is the input XML file (sample.xml):

<?xml version="1.0" encoding="utf-8"?>

<MyStudentsData>

    <Student student_type="Part-time">

        <Name>John</Name>

    </Student>

    <Student student_type="Full-time">

        <Name>Sean</Name>

    </Student>

    <Student student_type="Part-time">

        <Name>Sarah</Name>

    </Student>

</MyStudentsData>

Our goal here is to parse the above XML file using C++. Here is the C++ program to parse XML data using RapidXML. You can download the RapidXML library from Here.

#include <iostream>
#include <fstream>
#include <vector>
#include "rapidxml.hpp"

using namespace std;
using namespace rapidxml;


xml_document<> doc
xml_node<> * root_node = NULL;
   
int main(void)
{
    cout << "\nParsing my students data (sample.xml)....." << endl;
   
    // Read the sample.xml file
    ifstream theFile ("sample.xml");
    vector<char> buffer((istreambuf_iterator<char>(theFile)), istreambuf_iterator<char>());
    buffer.push_back('\0');
   
    // Parse the buffer
    doc.parse<0>(&buffer[0]);
   
    // Find out the root node
    root_node = doc.first_node("MyStudentsData");
   
    // Iterate over the student nodes
    for (xml_node<> * student_node = root_node->first_node("Student"); student_node; student_node = student_node->next_sibling())
    {
        cout << "\nStudent Type =   " << student_node->first_attribute("student_type")->value();
        cout << endl;
           
            // Interate over the Student Names
        for(xml_node<> * student_name_node = student_node->first_node("Name"); student_name_node; student_name_node = student_name_node->next_sibling())
        {
            cout << "Student Name =   " << student_name_node->value();
            cout << endl;
        }
        cout << endl;
    }
   
    return 0;
}

Example-2: Parse XML in C++ using PugiXML

In this example program, we will demonstrate how to parse xml using PugiXML library in C++. Here is the input XML file (sample.xml):

<?xml version="1.0" encoding="UTF-8" standalone="no" ?>

<EmployeesData FormatVersion="1">

    <Employees>

        <Employee Name="John" Type="Part-Time">

        </Employee>
       
        <Employee Name="Sean" Type="Full-Time">

        </Employee>
       
        <Employee Name="Sarah" Type="Part-Time">

        </Employee>

    </Employees>

</EmployeesData>

In this example program, we will demonstrate how to parse xml using pugixml library in C++. You can download the PugiXML library from Here.

#include <iostream>
#include "pugixml.hpp"

using namespace std;
using namespace pugi;

int main()
{
    cout << "\nParsing employees data (sample.xml).....\n\n";
   
   
    xml_document doc;
   
    // load the XML file
    if (!doc.load_file("sample.xml")) return -1;

    xml_node tools = doc.child("EmployeesData").child("Employees");

   
    for (xml_node_iterator it = tools.begin(); it != tools.end(); ++it)
    {
        cout << "Employees:";

        for (xml_attribute_iterator ait = it->attributes_begin(); ait != it->attributes_end(); ++ait)
        {
            cout << " " << ait->name() << "=" << ait->value();
        }

        cout << endl;
    }

    cout << endl;
   
    return 0;
   
}

Example-3: Parse XML in C++ using TinyXML

In this example program, we will demonstrate how to parse xml using TinyXML library in C++. Here is the input XML file (sample.xml):

<?xml version="1.0" encoding="utf-8"?>

<MyStudentsData>

    <Student> John </Student>

    <Student> Sean </Student>

    <Student> Sarah </Student>

</MyStudentsData>

In this example program, we will demonstrate how to parse xml using TinyXML library in C++. You can download the TinyXML library from Here.

#include <iostream>
#include <fstream>
#include <vector>
#include "tinyxml2.cpp"

using namespace std;
using namespace tinyxml2;
   

int main(void)
{
    cout << "\nParsing my students data (sample.xml)....." << endl;
   
    // Read the sample.xml file
    XMLDocument doc;
    doc.LoadFile( "sample.xml" );
   
    const char* title = doc.FirstChildElement( "MyStudentsData" )->FirstChildElement( "Student" )->GetText();
    printf( "Student Name: %s\n", title );

   
    XMLText* textNode = doc.LastChildElement( "MyStudentsData" )->LastChildElement( "Student" )->FirstChild()->ToText();
    title = textNode->Value();
    printf( "Student Name: %s\n", title );
   
   
    return 0;
}

Conclusion

In this article, we have briefly discussed XML and looked into three different examples of how to parse XML in C++. TinyXML is a minimalistic library for parsing XML data.  Most of the programmers mainly use the RapidXML or PugiXML to parse XML data.

]]>
C++ Bitwise Operators https://linuxhint.com/cplusplus-bitwise-operators/ Mon, 16 Nov 2020 12:17:39 +0000 https://linuxhint.com/?p=76917 In this article, we are going to discuss bitwise operators in the C++ programming language. We will see several working examples to understand bitwise operations in detail. In C++, the bitwise operators work on the individual bit level.

Brief Overview of Bitwise Operators

An operator is a symbol that instructs the compiler to perform certain mathematical or logical operations. There are several types of operators in C++, such as:

  1. Arithmetic Operators
  2. Logical Operators
  3. Relational Operators
  4. Assignment Operators
  5. Bitwise Operators
  6. Misc Operators

All the Bitwise operators work at the individual bit level. The bitwise operator can only be applied to the integer and character data types. For example, if you have an integer type variable with the size of 32 bits and you apply bitwise NOT operation, the bitwise NOT operator will be applied for all 32 bits. So, eventually, all the 32 bits in the variable will be inversed.

There are six different bitwise operators are available in C++:

  1. Bitwise OR [represented as “|”]
  2. Bitwise AND [represented as “&”]
  3. Bitwise NOT [represented as “~”]
  4. Bitwise XOR [represented as “^”]
  5. Bitwise Left Shift [represented as “<<”]
  6. Bitwise Right Shift [represented as “>>”]

Bitwise OR Truth Table

The Bitwise OR operator produces 1 when at least one operand is set to 1. Here is the truth table for the Bitwise OR operator:

Bit-1 Bit-2 Bit-1 | Bit-2
0 0 0
0 1 1
1 0 1
1 1 1

Bitwise AND Truth Table

Bitwise AND operator produces 1 when both the operands are set to 1. Here is the truth table for the Bitwise AND operator:

Bit-1 Bit-2 Bit-1 & Bit-2
0 0 0
0 1 0
1 0 0
1 1 1

Bitwise NOT Truth Table

Bitwise NOT operator inverts the operand. Here is the truth table for Bitwise NOT operator:

Bit-1 ~Bit-1
0 1
1 0

Bitwise XOR Truth Table

Bitwise XOR operator produces 1 if, and only if, one of the operands is set to 1. Here is the truth table for Bitwise AND operator:

Bit-1 Bit-2 Bit-1 ^ Bit-2
0 0 0
0 1 1
1 0 1
1 1 0

Bitwise Left Shift Operator

Bitwise Left Shift operator shifts all the bits left by the specified number of specified bits. If you left shift all the bits of the data by 1, the original data will be multiplied by 2. Similarly, if you left shift all the bits of the data by 2, the original data will be multiplied by 4.

Bitwise Right Shift Operator

Bitwise Right Shift operator shifts all the bits right by the specified number of specified bits. If you right shift all the bits of the data by 1, the original data will be divided (integer division) by 2. Similarly, if you right shift all the bits of the data by 2, the original data will be divided (integer division) by 4.

Examples

Now, since we have understood the basic concept of bitwise operations, let us look at a couple of examples, which will help you to understand the bitwise operations in C++:

  • Example-1: Bitwise OR Operator
  • Example-2: Bitwise AND Operator
  • Example-3: Bitwise NOT Operator
  • Example-4: Bitwise XOR Operator
  • Example-5: Bitwise Left Shift Operator
  • Example-6: Bitwise Right Shift Operator
  • Example-7: Set Bit
  • Example-8: Clear Bit

The example-7 and 8 are for demonstrating the real-world usage of bitwise operators in the C++ programming language.

Example-1: Bitwise OR Operator

In this example program, we will demonstrate the Bitwise OR operator.

#include <iostream>
#include <string>
#include <bitset>
using namespace std;

// display() function
void display(string print_msg, int number)
{
    bitset<16> myBitSet(number);

    cout << print_msg;
    cout << myBitSet.to_string() << " (" << myBitSet.to_ulong() << ") " << endl;
}

int main()
{
    int first_num = 7, second_num = 9, result = 0;

    // Bitwise OR operation
    result = first_num | second_num;

    // print the input numbers
    cout << endl;
    display("First Number is        =  ", first_num);
    display("Second Number is       =  ", second_num);

    // print the output value
    display("first_num | second_num =  ", result);
    cout << endl;

    return 0;
}

Example-2: Bitwise AND Operator

In this example program, we will illustrate Bitwise AND operator.

#include <iostream>
#include <string>
#include <bitset>
using namespace std;

// display() function
void display(string print_msg, int number)
{
    bitset<16> myBitSet(number);

    cout << print_msg;
    cout << myBitSet.to_string() << " (" << myBitSet.to_ulong() << ") " << endl;
}

int main()
{
    int first_num = 7, second_num = 9, result = 0;
    // Bitwise AND operation
    result = first_num & second_num;

    // print the input numbers
    cout << endl;
    display("First Number is        =  ", first_num);
    splay("Second Number is       =  ", second_num);

    // print the output value
    display("first_num & second_num =  ", result);
    cout << endl;

    return 0;
}

Example-3: Bitwise NOT Operator

In this example program, we will understand how Bitwise NOT operator works in C++.

#include <iostream>
#include <string>
#include <bitset>
using namespace std;

// display() function
void display(string print_msg, int number)
{
    bitset<16> myBitSet(number);
    cout << print_msg;
    cout << myBitSet.to_string() << " (" << myBitSet.to_ulong() << ") " << endl;
}

int main()
{
    int first_num = 7, second_num = 9, result_1 = 0, result_2 = 0;

    // Bitwise NOT operation
    result_1 = ~first_num;
    result_2 = ~second_num;

    // print the input numbers and output value
    cout << endl;
    display("First Number is    =  ", first_num);
    display("~first_num         =  ", result_1);
    cout << endl;

    // print the input numbers and output value
    display("Second Number is   =  ", second_num);
    display("~second_num        =  ", result_2);

    cout << endl;

    return 0;
}

Example-4: Bitwise XOR Operator

This program intends to explain how the Bitwise XOR operator works in C++.

#include <iostream>
#include <string>
#include <bitset>
using namespace std;

// display() function
void display(string print_msg, int number)
{
    bitset<16> myBitSet(number);
    cout << print_msg;
    cout << myBitSet.to_string() << " (" << myBitSet.to_ulong() << ") " << endl;
}

int main()
{
    int first_num = 7, second_num = 9, result = 0;

    // Bitwise XOR operation
    result = first_num ^ second_num;

    // print the input numbers
    cout << endl;
    display("First Number is        =  ", first_num);
    display("Second Number is       =  ", second_num);

    // print the output value
    display("first_num ^ second_num =  ", result);
    cout << endl;

    return 0;
}

Example-5: Bitwise Left Shift Operator

Now, we will see the example of the Bitwise Left Shift operator. In this program, we have declared two numbers, first_num and second_num of integer type. Here, the “first_num” is left-shifted by one bit, and the “second_num” is left-shifted by two bits.

#include <iostream>
#include <string>
#include <bitset>
using namespace std;

// display() function
void display(string print_msg, int number)
{
    bitset<16> myBitSet(number);
    cout << print_msg;
    cout << myBitSet.to_string() << " (" << myBitSet.to_ulong() << ") " << endl;
}

int main()
{
    int first_num = 7, second_num = 9, result_1 = 0, result_2 = 0;

    // Bitwise Left Shift operation
    result_1 = first_num << 1;
    result_2 = second_num << 2;

    // print the input numbers and output value
    cout << endl;
    display("First Number is    =  ", first_num);
    display("first_num << 1     =  ", result_1);
    cout << endl;

    // print the input numbers and output value
    display("Second Number is   =  ", second_num);
    display("second_num << 2    =  ", result_2);

    cout << endl;

    return 0;
}

Example-6: Bitwise Right Shift Operator

Now, we will see another example to understand the Bitwise Right Shift operator. We have declared two numbers, first_num and second_num of integer type. Here, the “first_num” is right-shifted by one bit, and the “second_num” is right-shifted by two bits.

#include <iostream>
#include <string>
#include <bitset>
using namespace std;

// display() function
void display(string print_msg, int number)
{
    bitset<16> myBitSet(number);
    cout << print_msg;
    cout << myBitSet.to_string() << " (" << myBitSet.to_ulong() << ") " << endl;
}

int main()
{
    int first_num = 7, second_num = 9, result_1 = 0, result_2 = 0;

    // Bitwise Right Shift operation
    result_1 = first_num >> 1;
    result_2 = second_num >> 2;

    // print the input numbers and output value
    cout << endl;
    display("First Number is    =  ", first_num);
    display("first_num >> 1     =  ", result_1);
    cout << endl;

    // print the input numbers and output value
    display("Second Number is   =  ", second_num);
    display("second_num >> 2    =  ", result_2);

    cout << endl;

    return 0;
}

Example-7: Set Bit

This example intends  to show how to set a particular bit using bitwise operators.

#include <iostream>
#include <string>
#include <bitset>
using namespace std;

// display() function
void display(string print_msg, int number)
{
    bitset<16> myBitSet(number);
    cout << print_msg;
    cout << myBitSet.to_string() << " (" << myBitSet.to_ulong() << ") " << endl;
}

int main()
{
    int first_num = 7, second_num = 9;

    // print the input number - first_num
    cout << endl;
    display("First Number is           =  ", first_num);

    // Set 5th bit
    first_num |= (1UL << 5);

    // Print output
    display("Set 5th bit of first_num  =  ", first_num);
    cout << endl;

    // print the input number - second_num
    cout << endl;
    display("Second Number is           =  ", second_num);// Set 6th bit
    second_num |= (1UL << 6);

    // Print output
    display("Set 6th bit of second_num  =  ", second_num);
    cout << endl;

    return 0;
}

Example-8: Clear Bit

This example intends to show how to clear a particular bit using bitwise operators.

#include <iostream>
#include <string>
#include <bitset>
using namespace std;

// display() function
void display(string print_msg, int number)
{
    bitset<16> myBitSet(number);
    cout << print_msg;
    cout << myBitSet.to_string() << " (" << myBitSet.to_ulong() << ") " << endl;
}

int main()
{
    int first_num = 7, second_num = 9;
   
    // print the input number - first_num
    cout << endl;
    display("First Number is           =  ", first_num);
   
    // Clear 2nd bit
    first_num &= ~(1UL << 2);

    // Print output
    display("Set 2nd bit of first_num  =  ", first_num);
    cout << endl;

    // print the input number - second_num
    cout << endl;
    display("Second Number is           =  ", second_num);

    // Clear 3rd bit
    second_num &= ~(1UL << 3);

    // Print output
    display("Set 3rd bit of second_num  =  ", second_num);
    cout << endl;

    return 0;
}

Conclusion

The bitwise operator is primarily used to manipulate the individual bits for integer and character data type. The bitwise operator is heavily used in embedded software development. So, if you are developing a device driver or a system very close to the hardware level, you may want to use these bitwise operators.

]]>
How to Read and Write to a File in C++ https://linuxhint.com/cplusplus_read_write/ Sat, 07 Nov 2020 13:08:13 +0000 https://linuxhint.com/?p=75889

In this article, we are going to show you how to read and write to a file in the C++ programming language by using several examples. To understand C++ file operations like read and write, we must first understand the concept of a stream in C++.

What is a Stream?

A stream is simply a flow of data or characters. There are two types of streams: input streams and output streams. An input stream is used to read the data from an external input device such as a keyboard, while an output stream is used to write data to the external output device such as a monitor. A file can be considered as both an input and output source.

In C++, we use a stream to send or to receive data to or from an external source.

We can use built-in classes to access an input/output stream, i.e., “ios”.

Here is the stream class hierarchy of the C++ programming language:

The “cin” and “cout” objects are used to read the data from the keyboard and to display the output on the monitor, respectively. In addition, “ifstream,” which stands for “input file stream,” is used to read a stream of data from a file, and “ofstream,” which stands for “output file stream,” is used to write a stream of data to a file.

The “iostram.h” file contains all the required standard input/output stream classes in the C++ programming language.

Examples

Now that you understand the basics of streams, we will discuss the following examples to help you to better understand file operations in C++:

  • Example 1: Open and Close a File
  • Example 2: Write to a File
  • Example 3: Read from a File
  • Example 4: Read and Write to a File
  • Example 5: Read and Write to a Binary File

Example 1: Open and Close a File

In this example program, we will demonstrate how to open/create a file and how to close the file in C++. As you can see in the below program, we have included the library required for file operations.

To open and close a file, we need an object of ofstream. Then, to read or write to a file, we have to open the file. We have included the fstream header file at line number-1 so that we can access ofstream class.

We have declared a myFile_Handler as an object of ofstream inside the main function. We can then use the open() function to create an empty file and the close() function to close the file.

#include <fstream>

using namespace std;

int main()
{
    ofstream myFile_Handler;

    // File Open
    myFile_Handler.open("File_1.txt");

    // File Close
    myFile_Handler.close();
    return 0;
}

Now, we will compile the program and examine the output. As you can see in the output window below, the “File_1.txt” file was created after executing the program. The size of the file is zero since we have not written any content in the file.

Example 2: Write to a File

In the previous example program, we showed you how to open a file and how to close the file. Now, we will show you how to write something in a file.

We can write to a file using the stream insertion operator, i.e., “<<”. In this program, we have used the file handler and insertion operator to write two lines in the file. The insertion operator (“<<”) indicates that we are inserting the string into the output file stream object.

#include <fstream>

using namespace std;

int main()
{
    ofstream myFile_Handler;
    // File Open
    myFile_Handler.open("File_1.txt");

    // Write to the file
    myFile_Handler << "This is a sample test File. " << endl;
    myFile_Handler << "This is the second line of the file. " << endl;

    // File Close
    myFile_Handler.close();
    return 0;
}

Now, we will compile the above program and execute it. As you can see below, we have successfully written to the file File_1.txt.

Example 3: Read from a File

In the previous examples, we showed you how to write content to a file. Now, let’s read the content from the file that we created in Example-2 and display the content on the standard output device, i.e., the monitor.

We use the getline() function to read the complete line from the file and then “cout” to print the line on the monitor.

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main()
{
    ifstream myFile_Handler;
    string myLine;

    // File Open in the Read Mode
    myFile_Handler.open("File_1.txt");

    if(myFile_Handler.is_open())
    {
        // Keep reading the file
        while(getline(myFile_Handler, myLine))
        {
            // print the line on the standard output
            cout << myLine << endl;
        }
    // File Close
    myFile_Handler.close();
    }
    else
    {
        cout << "Unable to open the file!";
    }
    return 0;
}

Now, we will print the content of File_1.txt using the following command:  cat File_1.txt. Once we compile and execute the program, it is clear that the output matches the content of the file. Therefore, we have successfully read the file and printed the content of the file to the monitor.

Example 4: Read and Write to a File

So far, we have showed you how to open, read, write, and close a file. In C++, we can also read and write to a file at the same time. To both read and write to a file, we have to get an fstream object and open the file in “ios::in” and “ios::out” mode.

In this example, we first write some content to the file. Then, we read the data from the file and print it to the monitor.

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main()
{
    fstream myFile_Handler;
    string myLine;

    // File Open
    myFile_Handler.open("File_1.txt", ios::in | ios::out);

    // Check if the file has opened
    if(!myFile_Handler)
    {
        cout << "File did not open!";
        exit(1);
    }

    // Write to the file
    myFile_Handler << "1. This is another sample test File. " << endl;
    myFile_Handler << "2. This is the second line of the file. " << endl;
   
    myFile_Handler.seekg(ios::beg);
   
    // Read the File
    if(myFile_Handler.is_open())
    {
        // Keep reading the file
        while( getline(myFile_Handler, myLine))
        {
            // print the line on the standard output
            cout << myLine << endl;
        }
       
        // File Close
        myFile_Handler.close();
    }
    else
    {
        cout << "Unable to open the file!";
    }
    myFile_Handler.close();
    return 0;
}

Now, we will compile and execute the program.

Example 5: Read and Write to a Binary File

In this example, we are going to declare a class and then write the object to a binary file. To simplify this example, we have declared the Employee class with a public variable emp_id. Then, we will read the binary file and print the output to the monitor.

#include <iostream>
#include <fstream>

using namespace std;

class Employee
{
public:
    int emp_id;
};

int main()
{
    ofstream binOutFile_Handler;
    ifstream binInFile_Handler;

    Employee empObj_W, empObj_R;

    // File Open
    binOutFile_Handler.open("Employee.dat", ios::out | ios::binary);

    // Check if the file has opened
    if(!binOutFile_Handler)
    {
        cout << "File did not open!";
        exit(1);
    }

    // Initialize empObj_W
    empObj_W.emp_id = 1512;

    // Write to the file
    binOutFile_Handler.write((char *) &empObj_W, sizeof(Employee));
    binOutFile_Handler.close();

    if(!binOutFile_Handler.good())
    {
        cout << "Error occured during writing the binary file!" << endl;
        exit(2);
    }

    // Now, let's read the employee.dat file
    binInFile_Handler.open("Employee.dat", ios::in | ios::binary);
    // Check if the file has opened
    if(!binInFile_Handler)
    {
        cout << "File did not open!";
        exit(3);
    }

    // Read the content of the binary file
    binInFile_Handler.read((char *) &empObj_R, sizeof(Employee));
    binInFile_Handler.close();

    if(!binInFile_Handler.good())
    {
        cout << "Error occured during reading the binary file!" << endl;
        exit(4);
    }

    // Print the output of empObj_R
    cout << "Details of the Employee : " << endl;
    cout << "Employee ID : " << empObj_R.emp_id << endl;

    return 0;
}

Conclusion

Files are mainly used to store the data, and they play an important role in real-world programming. In this article, we showed you how to use various file operations with the C++ programming language by working through several examples. Furthermore, we showed you how to read and write data into both text files and binary files.

]]>
Simple C++ Hello World Tutorial https://linuxhint.com/hello_world_cplusplus/ Sat, 07 Nov 2020 10:54:38 +0000 https://linuxhint.com/?p=75876 C++ is a flexible, general-purpose programming language that was originally created in 1985 by Bjarne Stroustrup, a Danish computer scientist. Today, C++ is considered to be one of the most powerful languages used for software development.

C++ is used in various domains, such as embedded software, real-time operating systems, game development, and finance, and because it supports both procedural and object-oriented programming styles, it is both strong and versatile.

In this article, we are going to discuss the basic structure of a C++ program and show you how to write a simple “Hello World” program.

C++ Program Structure

Before we write the “Hello World” program in C++, let us first discuss the primary elements of a C++ program. Here is an example of a C++ program skeleton:

Because every C++ program adheres to this basic structure, we will now explain the primary elements of this structure in depth.

The first line is “#include <iostream>”. Here, “iostream” stands for input/output stream, where a stream is a series of characters or bytes. This line instructs the preprocessor to include the content of the library in the program.

There are several libraries available in the C++ programming language. Libraries contain built-in objects and functions that programmers can use to write programs, and they are provided by the C++ compiler. When we install the C++ compiler, we get all the associated libraries.

The “iostream” includes the following objects:

  1. cin: the standard input stream
  2. cout: the standard output stream
  3. cerr: the standard output stream for errors
  4. clog: the output stream for logging

Every C++ program has a “main()” function. In this example, the value returned by the main function is an integer. Therefore, after the “main()” function is run here, a value of 0 will be returned.

The opening curly brace indicates the beginning of the body of the main function. The closing curly brace indicates the end of the body of the “main()” function. The rest of your code will be placed inside the curly braces

Hello World (HelloWorld.cpp)

Now, let us write a simple “Hello World” program and execute it. We will use the C++ standard library stream resources to write the string “Hello World” to the standard output.

#include <iostream>
int main()
{
    std::count << ”Hello World” << std::endl;
    return 0;
}

To compile the C++ program, you need to use the command g++ <filename> -o <output>.

We discussed the “iostream” header file in the previous section;  “cin” and “cout” are commonly used objects: “cin” is mainly used to get input from the keyboard and store the data as a variable, while “cout” is used to print the data on the screen.

We can use “cout” to display “Hello World” to the screen. However, we cannot use the “cout” object directly since it belongs to “std” namespace. Therefore, we use the scope resolution operator (i.e., ::). In addition, to print a new line, we used “std::endl”.

If you don’t use the scope resolution operator, you will get the following error:

#include <iostream>
int main()
{
    count << ”Hello World” << endl;
    return 0;
}

To fix the above error, you can either add the scope resolution operator correctly or you can mention the namespace at the beginning of the program. If you want to use “cout” without using the scope resolution operator, then you could write the following code:

#include <iostream>
using namespace std;
int main()
{
   
    count << ”Hello World” << endl;
    return 0;
}

In the above program, we mentioned the “std” namespace in the second line (i.e., “using namespace std;”). Therefore, we do not need to use the scope resolution operator every time we use an object from the “std” namespace, and we can simply use “cout” to print something to the standard output instead of writing “std::cout”. Similarly, we do not need to use the scope resolution operator for “endl”.

Now, we will compile this program and see the output:

As you can see, we get the same output.

Conclusion

C++ is a flexible, general-purpose programming language that is widely used in various domains. It is an extension of the C programming language and it inherits the syntax of C programming. In this article, we showed you how to write a simple “Hello World” program in the C++ programming language and explained various elements of the program.

]]>
Setting Decimal Precision in C Language https://linuxhint.com/setting_decimal_precision_c_-language/ Fri, 25 Sep 2020 02:53:21 +0000 https://linuxhint.com/?p=69090

This article will show you how to set decimal precision in C programming language. First, we will define precision, and then, we will look into multiple examples to show how to set decimal precision in C programming.

Decimal Precision in C

The integer type variable is normally used to hold the whole number and float type variable to hold the real numbers with fractional parts, for example, 2.449561 or -1.0587. Precision determines the accuracy of the real numbers and is denoted by the dot (.) symbol. The Exactness or Accuracy of real numbers is indicated by the number of digits after the decimal point. So, precision means the number of digits mentioned after the decimal point in the float number. For example, the number 2.449561 has precision six, and -1.058 has precision three.

32-bit single-precision floating-point number

As per IEEE-754 single-precision floating point representation, there are a total of 32 bits to store the real number. Of the 32 bits, the most significant bit is used as a sign bit, the following 8 bits are used as an exponent, and the following 23 bits are used as a fraction.64-bit single-precision floating-point number

In the case of IEEE-754 double-precision floating point representation, there are a total of 64 bits to store the real number. Of the 64 bits, the most significant bit is used as a sign bit, the following 11 bits are used as an exponent, and the following 52 bits are used as a fraction.

However, when printing the real numbers, it is necessary to specify the precision (in other words, accuracy) of the real number. If the precision is not specified, the default precision will be considered, i.e., six decimal digits after the decimal point. In the following examples, we will show you how to specify precision when printing floating-point numbers in the C programming language.

Examples

Now that you have a basic understanding of precision, let us look at a couple of examples:

    1. Default precision for float
    2. Default precision for double
    3. Set precision for float
    4. Set precision for double

Example 1: Default Precision for Float

This example shows that the default precision is set to six digits after the decimal point. We have initialized a float variable with the value 2.7 and printed it without explicitly specifying the precision.

In this case, the default precision setting will ensure that six digits after the decimal point are printed.

#include <stdio.h>

int main()
{
    float f = 2.7;

    printf("\nValue of f     =  %f \n", f);
    printf("Size of float    =  %ld \n", sizeof(float));
   
    return 0;
}

vbox - default precision

Example 2: Default Precision for Double

In this example, you will see that the default precision is set to six digits after the decimal point for double type variables. We have initialized a double variable, i.e., d, with the value 2.7 and printed it without specifying the precision. In this case, the default precision setting will ensure that six digits after the decimal point are printed.

#include <stdio.h>

int main()
{
    double d = 2.7;

    printf("\nValue of d      =  %lf \n", d);
    printf("Size of double  =  %ld \n", sizeof(double));
   
    return 0;
}

Default Precision for Double

Example 3: Set Precision for Float

Now, we will show you how to set precision for float values. We have initialized a float variable, i.e., f, with the value 2.7, and printed it with various precision settings. When we mention “%0.4f” in the printf statement, this indicates that we are interested in printing four digits after the decimal point.

#include <stdio.h>

int main()
{
    float f = 2.7;

    /* set precision for float variable */
    printf("\nValue of f (precision  = 0.1)     =  %0.1f \n", f);
    printf("\nValue of f (precision  = 0.2)     =  %0.2f \n", f);
    printf("\nValue of f (precision  = 0.3)     =  %0.3f \n", f);
    printf("\nValue of f (precision  = 0.4)     =  %0.4f \n", f);
   
    printf("\nValue of f (precision  = 0.22)    =  %0.22f \n", f);
    printf("\nValue of f (precision  = 0.23)    =  %0.23f \n", f);
    printf("\nValue of f (precision  = 0.24)    =  %0.24f \n", f);
    printf("\nValue of f (precision  = 0.25)    =  %0.25f \n", f);
    printf("\nValue of f (precision  = 0.40)    =  %0.40f \n", f);
   
    printf("Size of float  =  %ld \n", sizeof(float));
   
    return 0;
}

Set Precision for Float

Example 4: Set Precision for Double

In this example, we will see how to set precision for double values. We have initialized a double variable, i.e., d, with the value 2.7 and printed it with various precision settings. When we mention “%0.52f” in the printf statement, this indicates that we are interested in printing 52 digits after the decimal point.

#include <stdio.h>

int main()
{
    float f = 2.7;

    /* set precision for float variable */
    printf("\nValue of f (precision  = 0.1)     =  %0.1f \n", f);
    printf("\nValue of f (precision  = 0.2)     =  %0.2f \n", f);
    printf("\nValue of f (precision  = 0.3)     =  %0.3f \n", f);
    printf("\nValue of f (precision  = 0.4)     =  %0.4f \n", f);
   
    printf("\nValue of f (precision  = 0.22)    =  %0.22f \n", f);
    printf("\nValue of f (precision  = 0.23)    =  %0.23f \n", f);
    printf("\nValue of f (precision  = 0.24)    =  %0.24f \n", f);
    printf("\nValue of f (precision  = 0.25)    =  %0.25f \n", f);
    printf("\nValue of f (precision  = 0.40)    =  %0.40f \n", f);
   
    printf("Size of float  =  %ld \n", sizeof(float));
   
    return 0;
}

Set Precision for Double

Conclusion

Precision is a very important factor for representing a real number with adequate accuracy. The c programming language provides the mechanism to control the accuracy or exactness of a real number. However, we cannot change the actual precision of the real number. For example, the fraction part of a 32-bit single-precision floating-point number is represented by 23 bits, and this is fixed; we cannot change this for a particular system. We can only decide how much accuracy we want by setting the desired precision of the real number. If we need more accuracy, we can always use the 64-bit double-precision floating-point number.

]]>
How to use Strcpy() in C language? https://linuxhint.com/strcpy_c_language/ Fri, 18 Sep 2020 18:37:52 +0000 https://linuxhint.com/?p=68617 In this article, we are going to learn about the strcpy() function in the C programming language. The strcpy() function is a very popular standard library function to perform the string copy operation in the C programming language. There are several standard header files in C programming language to perform standard operations. The “string.h” is one of such header files, which provides several standard library functions to perform string operations. The “strcpy()” function is one of the library functions provided by “string.h”.

Syntax:

char* strcpy (char* destination_location, const char* source_string);

Understanding strcpy():

The sole purpose of the strcpy() function is to copy a string from source to destination. Now, lets us look at the above syntax of strcpy() function. The strcpy() function is capable of accepting two parameters –

  • char * destination
  • const char * source

The source is a constant here to ensure that the strcpy() function cannot change the source string. The strcpy() function copies all the characters (including the NULL character at the end of the string) from the source string to the destination. Once the copy operation is complete from source to destination, the strcpy() function returns the address of the destination back to the caller function.

The important point to notice here is, the strcpy() function does not append the source string with the destination string. It rather replaces the content of the destination with the content of the source string.

Also, the strcpy() function does not perform any checks to ensure that the size of the destination is more than the source string, it is completely the responsibility of the programmer.

Examples:

Now, we will see several examples to understand the strcpy() function:

  1. strcpy() – Normal Operation (example1.c)
  2. strcpy() – Case-1 (example2.c)
  3. strcpy() – Case-2 (example3.c)
  4. strcpy() – Case-3 (example4.c)
  5. strcpy() – User Defined Version (example5.c)
  6. strcpy() – User Defined Version Optimized (example6.c)

strcpy() – Normal Operation (example1.c):

This example program shows how to perform a normal string copy operation using the strcpy() function in the C programming language. Please note that the length of the destination string is 30 (char destination_str[30]; ), which is greater than the length of the source string (length is 18 including the NULL character) so that the destination can accommodate all the characters from the source string.

#include <stdio.h>
#include <string.h>
   
int main()
{
    char source_str[] = "www.linuxhint.com";
    char destination_str[30];          
   
    printf("Before calling strcpy() function : \n\n");
    printf("\tSource String       = %s\n", source_str);
    printf("\tDestination String  = %s\n\n", destination_str);
   
    strcpy(destination_str, source_str);  
   
    printf("After executing strcpy() function : \n\n");
    printf("\tSource String       = %s\n", source_str);
    printf("\tDestination String  = %s\n\n", destination_str);
   
    return 0;
}

strcpy() – Case-1 (example2.c):

The intent of this example program is to clearly explain what happens when the length of the destination string is less than the length of the source string. In such cases, the destination location will not have enough spaces/bytes to accommodate all the characters (including NULL character) from the source string. Two things, you should always keep in mind:

  1. The strcpy() function will not check if the destination has enough space.
  2. This could be dangerous in embedded software because the strcpy() will replace the memory area beyond the destination’s boundary.

Let us look at the example program. We have declared source_str and initialized it to “www.linuxhint.com”, which will take 18 bytes in memory to store, including the Null character at the end of the string. Then, we have declared another character array i.e. destination_str with the size of only 5. So, the destination_str cannot hold the source string with a total size of 18 bytes.

But, still, we are calling the strcpy() function to copy the source string to destination string. From the below output, we can see the strcpy() did not complain at all. In this case, the strcpy() function will start copying the character from the source string (until it finds the NULL character in the source string) to the destination address (even though destination boundary exceeds). That means the strcpy() function does not do any boundary checking for destination array. Eventually, the strcpy() function will overwrite the memory addresses which are not allocated to the destination array. This is why the strcpy() function will end up overwriting the memory locations which might be allocated to a different variable.

In this example, we can see from the below output, that the strcpy() function overwrites the source string itself. Programmers should always be careful with such behavior.

#include <stdio.h>
#include <string.h>
   
int main()
{
    char source_str[] = "www.linuxhint.com";
    char destination_str[5];
   
    printf("Before calling strcpy() function : \n\n");
    printf("\tSource String       = %s\n", source_str);
    printf("\tDestination String  = %s\n\n", destination_str);
   
    strcpy(destination_str, source_str);  
   
    printf("After executing strcpy() function : \n\n");
    printf("\tSource String       = %s\n", source_str);
    printf("\tDestination String  = %s\n\n", destination_str);
   
    //printf("Source Address      = %u (0x%x)\n", &source_str[0], &source_str[0]);
    //printf("Destination Address = %u (0x%x)\n", &destination_str[0], &destination_str[0]);
   
    return 0;
}

strcpy() – Case-2 (example3.c):

This program illustrates the situation when the destination string size is greater than the source string size and destination string is already initialized with some value. In this example, we have initialized:

  • source_str to “www.linuxhint.com” [size = 17+1 = 18]
  • destination_str to “I_AM_A_DESTINATION_STRING” [size = 25+1 = 26]

The strcpy() function will copy all the 17 characters and the NULL character from the source string to the destination string. But, it will not replace/change the remaining bytes (Byte 19 to 26, one based) in the destination array. We have used for loop to iterate over the destination array and print the whole array to prove that the bytes-19 to 26 are unchanged in the destination array. That is why we see the last output as:

www.linuxhint.com_STRING”.

#include <stdio.h>
#include <string.h>


/* This program illustrates the situation when :
   
    destination string size > source string size
   
    and we execute strcpy() function to copy the
    source string to destination.
   
    Note: The destination string size should always
    be greater than or equal to the source string.
*/

int main()
{
    char source_str[] = "www.linuxhint.com";
    char destination_str[26] = "I_AM_A_DESTINATION_STRING";
   
    printf("Before calling strcpy() function : \n\n");
    printf("\tSource String       = %s\n", source_str);
    printf("\tDestination String  = %s\n\n", destination_str);
   
    strcpy(destination_str, source_str);  
   
    printf("After executing strcpy() function : \n\n");
    printf("\tSource String       = %s\n", source_str);
    printf("\tDestination String  = %s\n\n", destination_str);

   
    /* print destination string using for loop*/   
    printf("Print the destination string char by char : \n\n");
    printf("\tDestination String  = ");
   
    for(int i=0; i<25;i++)
    {
        printf("%c", destination_str[i]);
    }
    printf("\n\n");
   
    return 0;
}

strcpy() – Case-3 (example4.c):

We have considered this program as an example to show that we should never call strcpy() with a string literal as the destination. This will cause undefined behavior and eventually, the program will crash.

#include <stdio.h>
#include <string.h>
   
int main()
{
    char source_str[] = "www.linuxhint.com";
   
    printf("Before calling strcpy() function : \n\n");
    printf("\tSource String       = %s\n", source_str);
   
    /* Never call strcpy() with string literal as destination.
       The program will crash.
    */

    strcpy("destination_str", source_str);  
   
    printf("After executing strcpy() function : \n\n");
    printf("\tSource String       = %s\n", source_str);
   
    return 0;
}

strcpy() – User Defined Version (example5.c):

In this example program, we have shown how to write a user-defined version of strcpy() function.

#include <stdio.h>
char * strcpy_user_defined(char *dest, const char * src);

/* User defined version of strcpy() function */
char * strcpy_user_defined(char *dest, const char * src)
{
    char * dest_backup = dest;
   
    while(*src != '\0')    /* Iterate until '\0' is found.*/
    {
        *dest = *src;     /* Copy source char to destination */
        src++;            /* Increment source pointer */
        dest++;         /* Increment destination pointer */
    }
   
    *dest = '\0';         /* Insert '\0' in destination explicitly*/
   
    return dest_backup;
}
   
int main()
{
    char source_str[] = "www.linuxhint.com";
    char destination_str[30];
   
    printf("Before calling user defined string copy function : \n\n");
    printf("\tSource String       = %s\n", source_str);
    printf("\tDestination String  = %s\n\n", destination_str);
   
    /* Calling user defined string copy function */
    strcpy_user_defined(destination_str, source_str);  
   
    printf("After executing user defined string copy function : \n\n");
    printf("\tSource String       = %s\n", source_str);
    printf("\tDestination String  = %s\n\n", destination_str);
   
    return 0;
}

strcpy() – User Defined Version Optimized (example6.c):

Now, in this example program, we are going to optimize the user-defined version of strcpy().

#include <stdio.h>
char * strcpy_user_defined(char *dest, const char * src);


/* Optimized version of user defined strcpy() function */
char * strcpy_user_defined(char *dest, const char * src)
{  
    char * dest_backup = dest;
   
    while(*dest++ = *src++)
    ;
   
    return dest_backup;
}
   
int main()
{
    char source_str[] = "www.linuxhint.com";
    char destination_str[30];
   
    printf("Before calling user defined string copy function : \n\n");
    printf("\tSource String       = %s\n", source_str);
    printf("\tDestination String  = %s\n\n", destination_str);
   
    /* Calling user defined string copy function */
    strcpy_user_defined(destination_str, source_str);  
   
    printf("After executing user defined string copy function : \n\n");
    printf("\tSource String       = %s\n", source_str);
    printf("\tDestination String  = %s\n\n", destination_str);
   
    return 0;
}

Conclusion:

The strcpy() function is a very popular and handy library function to perform the string copy operation in the C programming language. This is mainly used to copy the string from one location to another location. However, we want to reiterate the fact that the strcpy() function does not do the boundary checking for the destination array, which could lead to a serious software bug if ignored. It is always the responsibility of the programmer to make sure the destination array has enough space to hold all the characters from source string including the NULL character.

]]>
How to Use isalpha() in C Language https://linuxhint.com/use_isalpha_c_language/ Fri, 18 Sep 2020 11:06:17 +0000 https://linuxhint.com/?p=68555 There are several standard library header files in the C programming language used to perform various standard operations. The “ctype.h” is one such header file, and the “isalpha()” function is one of the library functions provided by “ctype.h.” The isalpha() library function is used to identify whether a character is an alphabet. In this article, you will learn about the isalpha() library function in C language.

Prototype of isalpha()

This is the prototype for the function in C programming language:

int isalpha (int character_input);

Understanding isalpha()

The isalpha() function is a library function provided by “ctype.h.” This function checks whether a character is an alphabet character. If the function detects that the input character is an alphabet character (‘A’ to ‘Z’ or ‘a’ to ‘z’), it returns a non-zero integer value. But if the input character is not an alphabet character, then the function returns zero.

If you look closely at the function prototype mentioned above, the function takes one argument of the integer type. However, when we call the isaplha() function, we pass a character (‘A’ to ‘Z’ or ‘a’ to ‘z’). The value of the character is converted into an integer value. In C language, a character is stored in the memory as the corresponding ASCII value. Each alphabet has a corresponding ASCII value. For example, the ASCII value for “A” is 65, “b” is 98, etc.

Note: ASCII stands for American Standard Code for Information Interchange. The complete ASCII table can be found at the following address:

https://www.cs.cmu.edu/~pattis/15-1XX/common/handouts/ascii.html

Examples

Now that you understand the isalpha() function and its syntax, let us look at a few examples:

  • Example 1: Upper-Case Alphabets
  • Example 2: Lower-Case Alphabets
  • Example 3: Digits
  • Example 4: Special Characters
  • Example 5: Practical Usage

Example 1: Upper-Case Alphabets

In this example, you will see how the isalpha() function detects upper-case alphabets.

#include <stdio.h>
#include <ctype.h>
   
int main()
{
    char char_input_1 = 'A';
    char char_input_2 = 'B';
    char char_input_3 = 'M';
    char char_input_4 = 'Y';
    char char_input_5 = 'Z';
   
    /* Check if char_input_1 is an alphabet */
    if(isalpha(char_input_1))
        printf("%c is an alphabet.\n",char_input_1);
    else
        printf("%c is not an alphabet.\n",char_input_1);
       
       
    /* Check if char_input_2 is an alphabet */
    if(isalpha(char_input_2))
        printf("%c is an alphabet.\n",char_input_2);
    else
        printf("%c is not an alphabet.\n",char_input_2);
       
       
    /* Check if char_input_3 is an alphabet */
    if(isalpha(char_input_3))
        printf("%c is an alphabet.\n",char_input_3);
    else
        printf("%c is not an alphabet.\n",char_input_3);
       
       
    /* Check if char_input_4 is an alphabet */
    if(isalpha(char_input_4))
        printf("%c is an alphabet.\n",char_input_4);
    else
        printf("%c is not an alphabet.\n",char_input_4);
       
       
    /* Check if char_input_5 is an alphabet */
    if(isalpha(char_input_5))
        printf("%c is an alphabet.\n",char_input_5);
    else
        printf("%c is not an alphabet.\n",char_input_5);
   
       
    return 0;
}

Example 2: Lower-Case Alphabets

In this example, you will see how the isalpha() function detects lower-case alphabets and returns a non-zero integer value.

#include <stdio.h>
#include <ctype.h>
   
int main()
{
    char char_input_1 = 'a';
    char char_input_2 = 'b';
    char char_input_3 = 'm';
    char char_input_4 = 'y';
    char char_input_5 = 'z';
   
    /* Check if char_input_1 is an alphabet */
    if(isalpha(char_input_1))
        printf("%c is an alphabet.\n",char_input_1);
    else
        printf("%c is not an alphabet.\n",char_input_1);
       
       
    /* Check if char_input_2 is an alphabet */
    if(isalpha(char_input_2))
        printf("%c is an alphabet.\n",char_input_2);
    else
        printf("%c is not an alphabet.\n",char_input_2);
       
       
    /* Check if char_input_3 is an alphabet */
    if(isalpha(char_input_3))
        printf("%c is an alphabet.\n",char_input_3);
    else
        printf("%c is not an alphabet.\n",char_input_3);
       
       
    /* Check if char_input_4 is an alphabet */
    if(isalpha(char_input_4))
        printf("%c is an alphabet.\n",char_input_4);
    else
        printf("%c is not an alphabet.\n",char_input_4);
       
       
    /* Check if char_input_5 is an alphabet */
    if(isalpha(char_input_5))
        printf("%c is an alphabet.\n",char_input_5);
    else
        printf("%c is not an alphabet.\n",char_input_5);
   
       
    return 0;
}

Example 3: Digits

In this example, you will see that the isalpha() function returns zero when we pass numerical digits.

#include <stdio.h>
#include <ctype.h>
   
int main()
{
    char char_input_1 = '0';
    char char_input_2 = '1';
    char char_input_3 = '2';
    char char_input_4 = '3';
    char char_input_5 = '4';
   
    /* Check if char_input_1 is an alphabet */
    if(isalpha(char_input_1))
        printf("%c is an alphabet.\n",char_input_1);
    else
        printf("%c is not an alphabet.\n",char_input_1);
       
       
    /* Check if char_input_2 is an alphabet */
    if(isalpha(char_input_2))
        printf("%c is an alphabet.\n",char_input_2);
    else
        printf("%c is not an alphabet.\n",char_input_2);
       
       
    /* Check if char_input_3 is an alphabet */
    if(isalpha(char_input_3))
        printf("%c is an alphabet.\n",char_input_3);
    else
        printf("%c is not an alphabet.\n",char_input_3);
       
       
    /* Check if char_input_4 is an alphabet */
    if(isalpha(char_input_4))
        printf("%c is an alphabet.\n",char_input_4);
    else
        printf("%c is not an alphabet.\n",char_input_4);
       
       
    /* Check if char_input_5 is an alphabet */
    if(isalpha(char_input_5))
        printf("%c is an alphabet.\n",char_input_5);
    else
        printf("%c is not an alphabet.\n",char_input_5);
   
       
    return 0;
}

Example 4: Special Characters

In this example, you will see that the isalpha() function returns zero when we pass special characters.

#include <stdio.h>
#include <ctype.h>
   
int main()
{
    char char_input_1 = '&';
    char char_input_2 = '$';
    char char_input_3 = '#';
    char char_input_4 = '%';
    char char_input_5 = '@';
   
    /* Check if char_input_1 is an alphabet */
    if(isalpha(char_input_1))
        printf("%c is an alphabet.\n",char_input_1);
    else
        printf("%c is not an alphabet.\n",char_input_1);
       
       
    /* Check if char_input_2 is an alphabet */
    if(isalpha(char_input_2))
        printf("%c is an alphabet.\n",char_input_2);
    else
        printf("%c is not an alphabet.\n",char_input_2);
       
       
    /* Check if char_input_3 is an alphabet */
    if(isalpha(char_input_3))
        printf("%c is an alphabet.\n",char_input_3);
    else
        printf("%c is not an alphabet.\n",char_input_3);
       
       
    /* Check if char_input_4 is an alphabet */
    if(isalpha(char_input_4))
        printf("%c is an alphabet.\n",char_input_4);
    else
        printf("%c is not an alphabet.\n",char_input_4);
       
       
    /* Check if char_input_5 is an alphabet */
    if(isalpha(char_input_5))
        printf("%c is an alphabet.\n",char_input_5);
    else
        printf("%c is not an alphabet.\n",char_input_5);
   
       
    return 0;
}

Example 5: Practical Usage

In this example, we will look into the practical usage of the isalpha() function in a real-world situation. Suppose that we are receiving an input character stream and we need to extract the meaningful alphabets from it. We can use the islpha() function to extract the alphabets from the input stream.

#include <stdio.h>
#include <ctype.h>
   
   
int main()
{
    char char_input[] = "5673&^%_SOF2*!";
    char char_output[10];
    int i = 0, j = 0;
   
    while(char_input[i] != '\0')
    {
        if(isalpha(char_input[i]))
        {
            char_output[j] = char_input[i];
            j++;
        }
        i++;
    }
    char_output[j] = '\0';
   
    printf("char_output = %s\n",char_output);  
       
    return 0;
}

Conclusion

In multiple examples of the practical usage of the isalpha() function, this article showed you how the isalpha() function plays a key role in detecting alphabet characters in the C programming language. This function is mainly used in embedded programming, where we receive a stream of characters and we need to extract meaningful alphabets from the input stream.

]]>
Sizeof operator in C language https://linuxhint.com/sizeof_c_language/ Fri, 11 Sep 2020 11:00:20 +0000 https://linuxhint.com/?p=68224 In this article, we are going to learn about the sizeof operator in C. It is a widely used unary operator in the embedded software development, which helps us to find out the size of the operand. Therefore, the return value of the sizeof operator helps us to understand the number of bytes allocated in the computer memory to hold the particular variable or data type.

Understanding Sizeof:

Before we dive into the sizeof operator discussion, Let us first understand the meaning of the operator. An Operator is represented by a token or symbol which is used to perform an operation such as addition, subtraction, multiplication, division, etc. upon values or variables (Operands). For example, “*” is the symbol that is used to represent the multiplication operation, and it works on two operands (result = a * b ;). This is an example of a binary operator.

However, if an operator works upon only one operand, we call such an operator as a unary operator. The sizeof operator is one of the unary operators that exist in C programming language and apparently, it operates only on one operand. The sizeof operator returns the size of the operand. That means, from the return value of Sizeof operator, we can clearly say how many bytes allocated to hold the particular operand in the computer memory.

A computer’s memory is a collection of memory units (i.e. byte). When sizeof (int) returns four in a particular computer system, we can say that an integer variable takes 4 bytes to hold its value in that specific computer system’s memory. Also, please note that the return value of the sizeof operator also depends on the machines that you are using (32-bit system or 64-bit system).

Syntax:

Sizeof(type)
Sizeof(expression)

The return type of sizeof is size_t.

Examples:

Now since we understand the sizeof operator and know the syntax, let us look at a couple of examples, which will help us to understand the concept in a better way.

  • Sizeof for built-in types (example1.c)
  • Sizeof for Array (example2.c)
  • Sizeof for user-defined types (example3.c)
  • Sizeof for variables (example4.c)
  • Sizeof for expression (example5.c)
  • Practical usage of sizeof (example6.c)

Sizeof for built-in types (example1.c):

In this program, we will see how the sizeof operator works for built-in data types such as int, char, float, double. Let us look at the program and output.

#include <stdio.h>
   
int main()
{
    printf("Size of char   =  %ld \n", sizeof(char));
    printf("Size of int    =  %ld \n", sizeof(int));
    printf("Size of float  =  %ld \n", sizeof(float));
    printf("Size of double =  %ld \n\n", sizeof(double));
   
    printf("Size of short int      =  %ld \n", sizeof(short int));
    printf("Size of long int       =  %ld \n", sizeof(long int));
    printf("Size of long long int  =  %ld \n", sizeof(long long int));
    printf("Size of long double    =  %ld \n", sizeof(long double));
   
    return 0;
}

Sizeof for Array (example2.c)

In this program, we will see how to use the sizeof operator for different types of array. In case of an array, the sizeof operator will return (No. of elements in the array * Sizeof (array type)). For example, when we declare an integer type array of 10 elements (int SmartPhones [10] ;), the sizeof(Smartphones) will return:

(No. of elements in SmartPhones * sizeof(int)) = (10 * 4) = 40

Let us look at the program and output.

#include <stdio.h>

int main()
{
    int SmartPhones[10];
    char SmartPhoneNames[10];
    double SmartPhonesPrice[10];
   
    printf("Size of int     =  %ld \n", sizeof(int));
    printf("Size of char    =  %ld \n", sizeof(char));
    printf("Size of double  =  %ld \n", sizeof(double));
   
   
    /* Find out the sizeof Array*/
    printf("Size of SmartPhones[10]       =  %ld \n", sizeof(SmartPhones));
    printf("Size of SmartPhoneNames[10]   =  %ld \n", sizeof(SmartPhoneNames));
    printf("Size of SmartPhonesPrice[10]  =  %ld \n", sizeof(SmartPhonesPrice));
   

    return 0;
}

Sizeof for user-defined types(example3.c):

In this example, we will see how to use sizeof operator for user-defined data types such as structure and union. Let’s use the program and understand the output.

Now, looking at the program, and we can manually calculate the size of SmartPhoneType. As you can see below, SmartPhoneType is a structure, and it contains the following elements:

  • Number of character type variable = 1 [sp_name]
  • Number of integer type variable= 1 [sp_version]
  • Number of float type variables= 3 [sp_length, sp_width, sp_height]

From the example-1, we have seen that:

    • Size of character is 1 byte
    • Size of an integer is 4 bytes
    • Size of a float is 4 bytes

Therefore, if we add up the size of all the elements in the structure, we should be able to get the size of the structure, i.e. SmartPhoneType. Therefore, the size of the structure should be = (1 + 4 + 4 + 4 + 4) bytes = 17 bytes. However, the program output says the structure size is 20. The extra 3 bytes (sp_name, which is a character, is taking 4 bytes instead of 1 byte) allocated for the structure due to the structure padding.

#include <stdio.h>

/* Create an user defined structure type - SmartPhoneType*/
struct SmartPhoneType
{
    char  sp_name;
    int   sp_version;
    float sp_length;
    float sp_width;
    float sp_height;
}SmartPhone;


/* Define an user defined union type - SmartPhoneUnionType*/
Union SmartPhoneUnionType
{
    char  sp_name;
    int   sp_version;
    float sp_length;
    float sp_width;
    float sp_height;
}SmartPhone_u;

   
int main()
{
    /* Find out the size of structure and union*/
    printf("Size of struct   =  %ld \n", sizeof(SmartPhone));
    printf("Size of union    =  %ld \n", sizeof(SmartPhone_u));
   
    return 0;
}

Sizeof for variables (example4.c):

This example program illustrates that the sizeof operator is capable of accepting the variable also and return the size of the variable.

#include <stdio.h>
   
int main()
{
    /* Declare char, int, float and double type variable and array */
    char   var_a, var_b[20];
    int    var_c, var_d[20];
    float  var_e, var_f[20];
    double var_g, var_h[20];
   
   
    /* Find out the size of variables and array.
       This program demonstrates that variable can also
       be used as an operand sizeof operator*/

   
    /* size of char, char variable and char array*/
    printf("Size of char        =  %ld \n", sizeof(char));
    printf("Size of var_a       =  %ld \n", sizeof(var_a));
    printf("Size of var_b[20]   =  %ld \n\n", sizeof(var_b));
   
   
    /* size of int, int variable and int array*/
    printf("Size of int         =  %ld \n", sizeof(int));
    printf("Size of var_c       =  %ld \n", sizeof(var_c));
    printf("Size of var_d[20]   =  %ld \n\n", sizeof(var_d));
   
   
    /* size of float, float variable and float array*/
    printf("Size of float       =  %ld \n", sizeof(float));
    printf("Size of var_e       =  %ld \n", sizeof(var_e));
    printf("Size of var_f[20]   =  %ld \n\n", sizeof(var_f));
   
   
    /* size of double, double variable and double array*/
    printf("Size of double      =  %ld \n", sizeof(double));
    printf("Size of var_g       =  %ld \n", sizeof(var_g));
    printf("Size of var_h[20]   =  %ld \n", sizeof(var_h));
   
    return 0;
}

Sizeof for expression(example5.c):

In this example program, we will demonstrate that the sizeof operator can also accept an expression and return the size of the resulting expression.

#include <stdio.h>

int main()
{
    int    var_a = 5, var_b = 3;
    double  var_c = 2.5, var_d = 4.5;
   
    printf("Size of int     =  %ld \n", sizeof(int));
    printf("Size of double  =  %ld \n\n", sizeof(double));
   
    printf("Size of var_a * var_b   =  %ld \n", sizeof(var_a * var_b));
    printf("Size of var_c * var_d   =  %ld \n", sizeof(var_c * var_d));
   
   
    /* Here we are multiplying an integer variable with a double variable.
       Therefore, sizeof operator will return the size of maximum sized
       variable i.e. double type variable.*/

    printf("Size of var_a * var_c   =  %ld \n", sizeof(var_a * var_c));
   
    return 0;
}

Practical usage of sizeof (example6.c):

This example program will help you to understand a practical use case of the sizeof operator. The Sizeof operator is very much useful while allocating the dynamic memory from heap using malloc. Let us look at the program and the output.

#include <stdio.h>
#include <stdlib.h>

typedef struct
{
    char  sp_name;
    int   sp_version;
    float sp_length;
    float sp_width;
    float sp_height;
} SmartPhoneType;

int main()
{
    /* Allocate memory in the Heap memory for holding five SmartPhoneType
       variables.
    */

    SmartPhoneType * SmartPhone_Ptr = (SmartPhoneType *)malloc(5 * sizeof(SmartPhoneType));
   
    if(SmartPhone_Ptr != NULL)
    {
        printf("Memory allocated for 5 SmartPhoneType structure variables in
                        the Heap memory.\n"
);
       
    }
    else
    {
        printf("Error occured during the heap memory allocation!");
    }
       
   
    return 0;
}

Conclusion:

The Sizeof is an important unary operator in the C programming language. It helps us in determining the size of primitive data types, user-defined data types, expressions, etc. in computer memory. The Sizeof operator plays an important role in allocating dynamic memory in C using malloc, calloc, etc. in the Heap memory.

]]>
How to use enum in C Language https://linuxhint.com/use_enum_c_language/ Fri, 04 Sep 2020 18:44:41 +0000 https://linuxhint.com/?p=67315 The enum program in the C programming language is used to define integral constant values, which is very helpful in writing clean and readable programs. Programmers normally use enumeration to define named integral constants in their programs to provide better readability and maintainability of the software. This article will discuss enum in detail.

Syntax

enum  <Enum Type Name> {
Enumeration_Constant_Element-1,  
Enumeration_Constant_Element-2,  
Enumeration_Constant_Element-3,  
…….........,
Enumeration_Constant_Element-n,  
    };

The default value of Enumeration_Constant_Element-1 is 0, the value of Enumeration_Constant_Element-2 is 1, the value of Enumeration_Constant_Element-3 is 2, and the value of Enumeration_Constant_Element-n is (n-1).

Deep Dive into Enum

Now, since we know the syntax to define the enumeration type, let us look at an example:

enum Error {   
             IO_ERROR,
             DISK_ERROR,
             NETWORK_ERROR
           };

The “enum” keyword must always be used to define the enumeration type. So, whenever you want to define an enumeration type, you must use the “enum” keyword before <Enum Type Name>. After the “enum” keyword, you must use a valid identifier to define the <Enum Type Name>.

In the above example, the compiler will assign IO_ERROR to the integral value: 0, DISK_ERROR to the integral value: 1 and NETWORK_ERROR to the integral value: 2.  By default, the first enum-element is always assigned the value 0, the next enum-element is assigned the value 1, and so on.

This default behaviour can be changed if necessary by assigning the constant integral value explicitly, as follows:

enum Error {   
IO_ERROR = 2,
            DISK_ERROR,
            NETWORK_ERROR = 8 ,
        PRINT_ERROR
           };

In this case, the IO_ERROR is explicitly assigned to a value of 2 by the programmer, DISK_ERROR is assigned to a value of 3 by the compiler, NETWORK_ERROR is explicitly assigned to the value of 8 by the programmer, and PRINT_ERROR is assigned to the next integral value of the previous enum element NETWORK_ERROR (i.e., 9) by the compiler.

So, you now understand how to define a user-defined enumeration type in C. Is it possible to declare a variable of enum type (as we can declare a variable of integer type)?  Yes, it is! You can declare the enum variable as follows:

enum Error Hw_Error;

Again, “enum” is the keyword here, “Error” is the enum type, and  “Hw_Error” is an enum variable.

We will now look at the following examples to understand the various usages of enum:

  • Example 1: Default enum definition usage
  • Example 2: Custom enum definition usage
  • Example 3: enum definition using constant expression
  • Example 4: enum scope

Example 1: Default enum Definition Usage

In this example, you will learn how to define the enumeration type with default constant values. The compiler will take care of assigning the default values to the enum elements. Below, you will see the example program and the corresponding output.

#include <stdio.h>

/* Define the enum type */
enum Error {
    IO_ERROR,
    DISK_ERROR,
    NETWORK_ERROR
    };
   
int main()
{
    enum Error Hw_Error;    /* Creating enum variable*/

    printf("Setting Hw_Error to IO_ERROR\n");
    Hw_Error = IO_ERROR;
    printf("Value of Hw_Error = %d \n",Hw_Error);

    printf("\nSetting Hw_Error to DISK_ERROR\n");
    Hw_Error = DISK_ERROR;
    printf("Value of Hw_Error = %d \n",Hw_Error);

    printf("\nSetting Hw_Error to NETWORK_ERROR\n");
    Hw_Error = NETWORK_ERROR;
    printf("Value of Hw_Error = %d \n",Hw_Error);

    return 0;
}

https://lh6.googleusercontent.com/0CHtUqkuIA-okDEPI0_5fZLU6lZ6Exz6DK4uUr63k5Ros863eqC-HmrvZ_LZBKbEvqeCVMCsnvXXhfrYJrBaxxfZBVoiMOHPzXeyxqQnCVf4hz0D4AJ-mPRJWjhIGA

Example 2: Custom enum Definition Usage

In this example, you will learn how to define the enumeration type with a custom constant value. Also, this example will help you understand how the custom constants initialization can be done in any random order. In this example, we have explicitly defined the constant value for the 1st and 3rd enum elements (i.e., IO_ERROR and NETWORK_ERROR, respectively), but we have skipped the explicit initialization for the 2nd and 4th elements. It is now the responsibility of the compiler to assign the default values to the 2nd and 4th enum elements (i.e., DISK_ERROR and PRINT_ERROR, respectively). DISK_ERROR will be assigned to a value of 3 and PRINT_ERROR will be assigned to a value of 9. Below, you will see the example program and the output.

#include <stdio.h>

/* Define the enum type  - Custom initialization*/
enum Error {
    IO_ERROR = 2,
    DISK_ERROR,
    NETWORK_ERROR = 8,
    PRINT_ERROR
    };
   
int main()
{

    /* Declare enum variable*/
    enum Error Hw_Error;

    printf("Setting Hw_Error to IO_ERROR\n");
    Hw_Error = IO_ERROR;
    printf("Value of Hw_Error = %d \n",Hw_Error);

    printf("\nSetting Hw_Error to DISK_ERROR\n");
    Hw_Error = DISK_ERROR;
    printf("Value of Hw_Error = %d \n",Hw_Error);

    printf("\nSetting Hw_Error to NETWORK_ERROR\n");
    Hw_Error = NETWORK_ERROR;
    printf("Value of Hw_Error = %d \n",Hw_Error);
   
    printf("\nSetting Hw_Error to PRINT_ERROR\n");
    Hw_Error = PRINT_ERROR;
    printf("Value of Hw_Error = %d \n",Hw_Error);

    return 0;
}

https://lh6.googleusercontent.com/hKtv00Hj7iPnnlNhC7mu1v7hzPhB64C9nyHwjB6oQgyCyEwOgiLSYWDOxvQCDrhumn4IzqhkN4qF9HcuGZ9thqlBLy6hsv9F-FwKl2EnUjzx0af4UwDK0agfEVv0rA

Example 3: Enum Definition Using Constant Expression

In this example, you will learn how to use the constant expression to define the constant value for enum elements.

#include <stdio.h>

/* Define the enum type - custom initialization using constant expression
   constant expression is being used here in case of :
    a. IO_ERROR and
    b. NETWORK_ERROR
   This is an unusual way of defining the enum elements; however, this
program demonstrates that this way of enum elements initialization is possible in c.
*/


enum Error {
    IO_ERROR = 1 + 2 * 3 + 4,
    DISK_ERROR,
    NETWORK_ERROR = 2 == 2,
    PRINT_ERROR
    };
   
int main()
{

    /* Declare enum variable*/
    enum Error Hw_Error;

    printf("Setting Hw_Error to IO_ERROR\n");
    Hw_Error = IO_ERROR;
    printf("Value of Hw_Error = %d \n",Hw_Error);

    printf("\nSetting Hw_Error to DISK_ERROR\n");
    Hw_Error = DISK_ERROR;
    printf("Value of Hw_Error = %d \n",Hw_Error);

    printf("\nSetting Hw_Error to NETWORK_ERROR\n");
    Hw_Error = NETWORK_ERROR;
    printf("Value of Hw_Error = %d \n",Hw_Error);
   
    printf("\nSetting Hw_Error to PRINT_ERROR\n");
    Hw_Error = PRINT_ERROR;
    printf("Value of Hw_Error = %d \n",Hw_Error);

    return 0;
}

https://lh4.googleusercontent.com/9FAbPOnM95LiP_UQvg40oHSW4sv34aqpFgasbHMiy06Z_rKEom81TuMCVsfxWaZedtQOMEQx7ef_5qEfRVcNrUvhitDzOcTvYXregm4Udaby1NmwOil_Qhpr_oD4UQ

Example 4: enum Scope

In this example, you will learn how the scoping rule works for enum. A MACRO (#define) could have been used to define a constant instead of the enum, but the scoping rule does not work for MACRO.

#include <stdio.h>

int main()
{

    /* Define the enum type */
    enum Error_1 {
            IO_ERROR = 10,
            DISK_ERROR,
            NETWORK_ERROR = 3,
            PRINT_ERROR
             };
   

    {
   
        /* Define the enum type in the inner scope*/
        enum Error_1 {
                IO_ERROR = 20,
                DISK_ERROR,
                NETWORK_ERROR = 35,
                PRINT_ERROR
                 };

        /* Declare enum variable*/
        enum Error_1 Hw_Error;
        printf("Setting Hw_Error to IO_ERROR\n");
        Hw_Error = IO_ERROR;
        printf("Value of Hw_Error = %d \n",Hw_Error);

        printf("\nSetting Hw_Error to DISK_ERROR\n");
        Hw_Error = DISK_ERROR;
        printf("Value of Hw_Error = %d \n",Hw_Error);

        printf("\nSetting Hw_Error to NETWORK_ERROR\n");
        Hw_Error = NETWORK_ERROR;
        printf("Value of Hw_Error = %d \n",Hw_Error);
   
        printf("\nSetting Hw_Error to PRINT_ERROR\n");
        Hw_Error = PRINT_ERROR;
        printf("Value of Hw_Error = %d \n",Hw_Error);
    }
    return 0;
}

Comparison Between enum and macro

Enum Macro
Scoping rule is applicable for enum. Scoping rule is not applicable for Macro.
Default Enum value assignment happens automatically.

Enum is very helpful in defining a large number of constants. The compiler takes the default constant value initialization.

The macro constant values must always be mentioned explicitly by the programmer.

This could be a tedious process for a large number of constants since the programmer must always manually define each constant value while defining the Macro.

Conclusion

The enum program in C could be considered an optional method for standalone programs or small-sized projects since programmers can always use macro instead of an enum. However, experienced programmers tend to use enum over macro for large-scale software development projects. This helps in writing clean and readable programs.

]]>